rename
This commit is contained in:
12
serde_json/Cargo.toml
Normal file
12
serde_json/Cargo.toml
Normal file
@@ -0,0 +1,12 @@
|
||||
[package]
|
||||
name = "serde-json-test"
|
||||
version = "0.1.0"
|
||||
authors = ["Hatter Jiang <jht5945@gmail.com>"]
|
||||
edition = "2018"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
chrono = "0.4.10"
|
||||
80
serde_json/src/main.rs
Normal file
80
serde_json/src/main.rs
Normal file
@@ -0,0 +1,80 @@
|
||||
#[macro_use]
|
||||
extern crate serde_json;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Result, Value};
|
||||
use chrono::{DateTime, Utc, TimeZone};
|
||||
|
||||
mod my_date_format {
|
||||
use chrono::{DateTime, Utc, TimeZone};
|
||||
use serde::{self, Deserialize, Serializer, Deserializer};
|
||||
|
||||
const FORMAT: &'static str = "%Y-%m-%d %H:%M:%S";
|
||||
|
||||
pub fn serialize<S>(date: &DateTime<Utc>, serializer: S ) -> Result<S::Ok, S::Error> where S: Serializer {
|
||||
let s = format!("{}", date.format(FORMAT));
|
||||
serializer.serialize_str(&s)
|
||||
}
|
||||
|
||||
pub fn deserialize<'de, D>(deserializer: D ) -> Result<DateTime<Utc>, D::Error> where D: Deserializer<'de> {
|
||||
let s = String::deserialize(deserializer)?;
|
||||
Utc.datetime_from_str(&s, FORMAT).map_err(serde::de::Error::custom)
|
||||
}
|
||||
}
|
||||
|
||||
// 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,
|
||||
#[serde(with = "my_date_format")]
|
||||
timestamp: DateTime<Utc>,
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let serialized = serde_json::to_string(&TestStruct{
|
||||
ty: TestEnum::TypeA,
|
||||
timestamp: Utc.datetime_from_str("2020-01-28 17:04:00", "%Y-%m-%d %H:%M:%S").map_err(serde::de::Error::custom)?,
|
||||
})?;
|
||||
|
||||
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(())
|
||||
}
|
||||
Reference in New Issue
Block a user