jsonにシリアライズする際に、serde_json::to_string(&names).unwrap();としてしまうと、String型になってしまうため、デシリアライズの方法がわからなくなる。そのため、vectorにstructを入れたら、to_stringとせずにそのままjson化する。
use axum::{routing::get, Json, Router}; use serde_json::{json, Value}; use serde::{Serialize, Deserialize}; use std::io::BufReader; #[derive(Serialize, Deserialize, Debug)] struct Name { family: String, first: String, age: u32, } fn main() { let json_data = json(); println!("{:?}", &json_data); let deserialized = json!(**&json_data); println!("{:?}", &deserialized); let objs: Vec<Name> = serde_json::from_value(deserialized).unwrap(); println!("{:?}", objs); for obj in &objs { println!("{:?}", &obj); } } fn json() -> Json<Value> { let n1 = Name { family: "Yamada".to_string(), first: "Taro".to_string(), age: 20 }; let n2 = Name { family: "Tanaka".to_string(), first: "Hanako".to_string(), age: 18 }; let mut names: Vec<Name> = Vec::new(); names.push(n1); names.push(n2); Json(json!(names)) }
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.60s
Running `target/debug/axum`
Json(Array [Object {“age”: Number(20), “family”: String(“Yamada”), “first”: String(“Taro”)}, Object {“age”: Number(18), “family”: String(“Tanaka”), “first”: String(“Hanako”)}])
Array [Object {“age”: Number(20), “family”: String(“Yamada”), “first”: String(“Taro”)}, Object {“age”: Number(18), “family”: String(“Tanaka”), “first”: String(“Hanako”)}]
[Name { family: “Yamada”, first: “Taro”, age: 20 }, Name { family: “Tanaka”, first: “Hanako”, age: 18 }]
Name { family: “Yamada”, first: “Taro”, age: 20 }
Name { family: “Tanaka”, first: “Hanako”, age: 18 }