evestera / json_typegen

Tools and libraries to create types for Rust, Kotlin, TypeScript and Python from JSON samples
https://typegen.vestera.as
Apache License 2.0
268 stars 26 forks source link

Make it always valid to use the requested type name for the parsed data #20

Closed evestera closed 3 years ago

evestera commented 3 years ago

Code like this should preferably always be legal:

json_typegen!("<typename>", <valid source>);
// ...
let foo: <typename> = <parsed JSON with same shape as source>;

Cases where that is currently not the case:

The source JSON is a collection. The typename will be used as the type of the elements of the collection. E.g. json_typegen!("Foobar", ... will require you to parse to Vec<Foobar>.

Code generation tries to be "helpful" and create a more suitable type name, e.g.

json_typegen!("point", r#"{ "x": 1, "y": 2 }"#); will create the type Point

json_typegen!("foo_bar", r#"{ "x": 1, "y": 2 }"#); will create the type FooBar

json_typegen!("Points", r#"[{ "x": 1, "y": 2 }]"#); will create the type Point, so you get a Vec<Point>, but will not define Points

For all cases where the requested type name is legal it should be possible to just reserve the name up front, and then add an alias. Just have to make sure to allow a named root type to use the requested type (e.g. type Point = Point1; struct Point1 { ... } would be a bit silly`).