JSON serialization/deserialization
This is full-featured modern JSON implementation according to ECMA-404 standard.
This crate allows deserialization of JSON io::Read
stream into primitive types (bool
, i32
, etc.),
String and any other types that implement special trait called TryFromJson, which can be implemented
automatically through #[derive(TryFromJson)]
for your structs and enums.
And serialization back to JSON through DebugToJson trait, that acts like Debug
, allowing to
print your objects with println!()
and such.
It allows to read whitespece-separated JSON values from stream in sequence.
This implementation avoids unnecessary memory allocations and temporary object creations.
Examples
Deserializing simple values
use Reader;
let mut reader = new;
let the_true: bool = reader.read.unwrap;
let the_hundred_point_five: f32 = reader.read.unwrap;
let the_hello: String = reader.read.unwrap;
let the_array: = reader.read.unwrap;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
First need to create a Reader object giving it something that implements std::io::Read
. In example above i use &[u8]
.
Then call reader.read() to read each value from stream to some variable that implements TryFromJson
.
This crate has implementation of TryFromJson
for many primitive types, Vec
, HashMap
, and more.
Deserializing any JSON values
use ;
use TryInto;
let mut reader = new;
let the_true: Value = reader.read.unwrap;
let the_hundred_point_five: Value = reader.read.unwrap;
let the_hello: Value = reader.read.unwrap;
let the_array: Value = reader.read.unwrap;
assert_eq!;
let the_hundred_point_five: f32 = the_hundred_point_five.try_into.unwrap;
assert_eq!;
assert_eq!;
assert_eq!;
We have generic Value type that can hold any JSON node.
Deserializing/serializing objects
use ;
let mut reader = new;
let obj: Geometry = reader.read.unwrap;
println!;
See TryFromJson, DebugToJson.
Serializing scalar values
You can println!() word "true" or "false" to serialize a boolean. Also numbers can be printed as println!() does by default. The format is JSON-compatible. To serialize a &str, you can use escape function.
Alternatively you can create a Value object, and serialize it.
Skipping a value from stream
To skip current value without storing it (and allocating memory), read it to the ()
type.
use Reader;
let mut reader = new;
let _: = reader.read.unwrap;
let _: = reader.read.unwrap;
let _: = reader.read.unwrap;
let _: = reader.read.unwrap;
License: MIT