把遇到的情景记录在这里,大部分是官网的例子。以后会不定期更新。
将json字符串转换为json对象
use serde_json::{Result, Value};
fn untyped_example() -> Result<()> {
// Some JSON input data as a &str. Maybe this comes from the user.
let 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)?;
// Access parts of the data by indexing with square brackets.
println!("Please call {} at the number {}", v["name"], v["phones"][0]);
Ok(())
}
将json字符串转换为强类型对象
将json对象转换成结构体,需要在结构体上写#[derive(Serialize, Deserialize)]