Files
simple-rust-tests/serde-json-test/src/main.rs
2020-01-19 00:50:26 +08:00

60 lines
1.2 KiB
Rust

#[macro_use]
extern crate serde_json;
use serde::{Deserialize, Serialize};
use serde_json::{Result, Value};
// https://serde.rs/container-attrs.html
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
enum TestEnum {
#[serde(rename = "A")]
TypeA,
#[serde(rename = "B")]
TypeB,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
struct TestStruct {
ty: TestEnum,
}
fn main() -> Result<()> {
let serialized = serde_json::to_string(&TestStruct{
ty: TestEnum::TypeA,
})?;
println!("{}", serialized);
let data = r#"
{
"name": "John Doe",
"age": 43,
"phones": [
"+44 1234567",
"+44 2345678"
]
}"#;
let v: Value = serde_json::from_str(data)?;
println!("{}", v);
let mut john = json!({
"name": "John Doe",
"age": 43,
"phones": [
"+44 1234567",
"+44 2345678"
]
});
println!("{}", &john);
if let Option::Some(ref mut m) = john.as_object_mut() {
m.insert("test".into(), Value::Bool(true));
m.insert("test2".into(), Value::String("hello world".into()));
}
println!("{}", john);
Ok(())
}