jsonデータを読み込んで、書き換え
use serde::{Serialize, Deserialize}; use std::fs; use std::fs::File; use std::io::prelude::*; #[derive(Serialize, Deserialize, Debug)] #[allow(non_snake_case)] struct Rotator { Pitch:f32, Roll:f32, Yaw:f32, } #[derive(Serialize, Deserialize, Debug)] #[allow(non_snake_case)] struct CharaParam { Name: String, Id: i32, ItemIdList: Vec<u32>, RotData: Rotator, } fn main(){ let input_fn = fs::read_to_string("test_input.json") .expect("JSON Read Failed."); let mut param_list: Vec<CharaParam> = serde_json::from_str(&input_fn).unwrap(); let chara00 = CharaParam{Name:String::from("Apple"), Id:0x01, ItemIdList:vec![1000, 1001], RotData:Rotator{Pitch:0.0, Roll:0.0, Yaw:32.0} }; let chara01 = CharaParam{Name:String::from("Banana"), Id:0x02, ItemIdList:vec![1002, 1003], RotData:Rotator{Pitch:0.0, Roll:-70.0, Yaw:66.0}}; param_list.push(chara00); param_list.push(chara01); let output_fn = String::from("test_output.json"); let result = output_json(&output_fn, param_list); match result { Ok(..) => { println!("Json output finished.【{}】", output_fn) } Err(err) => { println!("Error: {}", err)} } } fn output_json(output_fn: &str, charaparam_list: Vec<CharaParam>) -> std::io::Result<()>{ let serialized: String = serde_json::to_string(&charaparam_list).unwrap(); let mut file = File::create(output_fn)?; file.write_all(serialized.as_bytes())?; Ok(()) }
[{“Name”:”Kiwi”,”Id”:3,”ItemIdList”:[2000,2001],”RotData”:{“Pitch”:0.0,”Roll”:0.0,”Yaw”:0.0}},{“Name”:”Orange”,”Id”:4,”ItemIdList”:[2002,2003],”RotData”:{“Pitch”:1.0,”Roll”:50.2,”Yaw”:66.5}},{“Name”:”Apple”,”Id”:1,”ItemIdList”:[1000,1001],”RotData”:{“Pitch”:0.0,”Roll”:0.0,”Yaw”:32.0}},{“Name”:”Banana”,”Id”:2,”ItemIdList”:[1002,1003],”RotData”:{“Pitch”:0.0,”Roll”:-70.0,”Yaw”:66.0}}]
書き込みは出来ていますが、処理量が増えてくると処理が冗長になるように思います。