Crate json_typegen[−][src]
Expand description
This crate provides the procedural macro json_typegen!
which creates Rust
types from JSON samples. As an example, the below code generates code for
the type Point, including derives for serialization and deserialization
(using serde_derive).
use json_typegen::json_typegen;
json_typegen!("Point", r#"{ "x": 1, "y": 2 }"#);
fn main() {
let mut p: Point = serde_json::from_str(r#"{ "x": 3, "y": 5 }"#).unwrap();
println!("deserialized = {:?}", p);
p.x = 4;
let serialized = serde_json::to_string(&p).unwrap();
println!("serialized = {}", serialized);
}
[dependencies]
serde = "1.0"
serde_derive = "1.0"
serde_json = "1.0"
json_typegen = "0.7"
The sample json can also come from local or remote files, like so:
ⓘ
json_typegen!("Point", "json_samples/point.json");
json_typegen!("Point", "http://example.com/someapi/point.json");
Conditional compilation
To avoid incurring the cost of a http request per sample used for every build you can use conditional compilation to only check against remote samples when desired:
ⓘ
#[cfg(not(feature = "online-samples"))]
json_typegen!("Point", r#"{ "x": 1, "y": 2 }"#);
#[cfg(feature = "online-samples")]
json_typegen!("Point", "https://typegen.vestera.as/examples/point.json");
And in Cargo.toml:
[features]
online-samples = []
You can then verify that remote samples match your expectations in e.g. CI builds as follows:
cargo check --features "online-samples"
Macros
Generate serde-compatible types from JSON