Serdes
Objective: Define a simple class and create an instance. Serialize the object into JSON. Finally deserialize JSON into new object.
Python
import json
from dataclasses import dataclass, asdict
@dataclass
class Person:
name: str
height: float
person_a = Person("Greg", 1.80)
json_text_a = json.dumps(asdict(person_a))
print(json_text_a)
json_text_b = '{"name":"Tom", "height": 1.85}'
person_b = Person(**json.loads(json_text_b))
print(person_b)
Notes regarding deserialization:
- Types are not checked. Use dacite or pydantic if needed.
- Extra arguments raise an exception.
- Missing arguments raise an exception, unless default values are provided.
Rust
Stdlib doesn't support serialization/deserialization to/from JSON. Crate serde has been used.
use serde::{Serialize, Deserialize}; #[derive(Default)] #[derive(Serialize, Deserialize, Debug)] struct Person { name: String, height: f64, } fn main() { let person_a = Person {name: "Greg".to_string(), height: 1.80}; let json_text_a = serde_json::to_string(&person_a).unwrap(); println!("{}", json_text_a); let json_text_b = r#"{"name":"Tom", "height": 1.85}"#; let person_b: Person = serde_json::from_str(&json_text_b).unwrap(); println!("{:?}", person_b); }
Notes regarding deserialization:
- Incorrect types result in error.
- Extra arguments are allowed and ignored.
- Missing arguments result in error.
Crystal
#![allow(unused)] fn main() { require "json" class Person include JSON::Serializable property name : String property height : Float64 def initialize(@name, @height) end end person_a = Person.new("Greg", 1.80) json_text_a = person_a.to_json puts json_text_a json_text_b = %({"name":"Tom", "height": 1.85}) person_b = Person.from_json(json_text_b) p! person_b }
Notes regarding deserialization:
- Incorrect types raise an exception.
- Extra arguments are allowed and ignored.
- Missing arguments raise an exception, unless default values are provided.