### Jsonの読み込み
use serde::{Serialize, Deserialize}; use std::fs; 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 deserialized: Vec<CharaParam> = serde_json::from_str(&input_fn).unwrap(); for data in &deserialized { println!("{:?}", data); } }
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.67s
Running `target/debug/sample`
CharaParam { Name: “Kiwi”, Id: 3, ItemIdList: [2000, 2001], RotData: Rotator { Pitch: 0.0, Roll: 0.0, Yaw: 0.0 } }
CharaParam { Name: “Orange”, Id: 4, ItemIdList: [2002, 2003], RotData: Rotator { Pitch: 1.0, Roll: 50.2, Yaw: 66.5 } }
### Jsonの書き込み
use serde::{Serialize, Deserialize}; 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 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}}; let mut param_list:Vec<CharaParam> = Vec::new(); 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(()) }
読み込み、書き込みはわかったが、書き込み時に、最終行にappendとしたい。。果たして出来るんか??
単純にjsonファイルを読み取って、vectorにデータを追加してjsonファイルに保存で良い?