# doc: https://crates.io/crates/serde[dependencies]
serde_json ="1.0"
serde ={ version ="1.0", features =["derive"]}
示例
useserde::{Deserialize,Serialize};useserde_json::{Result,Value};structJson{}implJson{fnparse_json_str(&self){// 使用json库 doc: https://crates.io/crates/json// 将json字符串解析为json对象let json_s =json::parse(r#"
{
"code": 200,
"success": true,
"payload": {
"features": [
"awesome",
"easyAPI",
"lowLearningCurve"
]
}
}
"#,).unwrap();println!("{:?}", json_s);println!("{:?}", json_s["code"]);// 将json对象转字符串let data =vec![1,2,3];println!("{:?}",json::stringify(data));// 构建一个json对象,使用宏letmut student =object!{"name"=>"xiaohong","age"=>1,"hobby"=>array!["basketball","football"],"score"=>object!{"math":92,"english":90}};println!("{:?}", student.dump());println!("{:?}", student["name"]);assert_eq!(student["name"],"xiaohong");}fntest_serde_json(&self){// 使用serde_json解析数据 doc: https://crates.io/crates/serdelet data =r#"
{
"name": "John Doe",
"age": 43,
"phones": [
"+44 1234567",
"+44 2345678"
]
}"#;// Parse the string of data into serde_json::Value.let v:Value=serde_json::from_str(data).unwrap();// Access parts of the data by indexing with square brackets.println!("Please call {} at the number {}", v["name"], v["phones"][0]);// json序列化#[derive(Serialize, Deserialize, Debug)]structPoint{
x:i32,
y:i32,}let point =Point{ x:1, y:2};// 实例化对象// Convert the Point to a JSON string.let serialized =serde_json::to_string(&point).unwrap();// 将对象str化// Prints serialized = {"x":1,"y":2}println!("serialized = {}", serialized);// Convert the JSON string back to a Point.let deserialized:Point=serde_json::from_str(&serialized).unwrap();// 将str转为对象// Prints deserialized = Point { x: 1, y: 2 }println!("deserialized = {:?}", deserialized);println!("{}", deserialized.x)}}pubfntest_json(){let j =Json{};// j.parse_json_str();
j.test_serde_json()}