I am trying to access from Rust via RESTful API services from Amadeus API travel.
The JSON responses are sometimes simple and sometimes more complex
Here is one example:
Here is another:
I would like to benefit from Rust strong typing to access the JSON data inside Rust program.
Are there any tools I can use to provide a JSON document as input (as above) which will generate the Rust struct and/or enum source code for me to use Rust strong typing?
Hello, I'm on my phone at the moment so can't say a lot but give this a try. You paste in the JSON and it generates the proper struct for you to use with serde.
Is that what you are looking for?
yes, thank you!
I tried it now on one very long JSON (in original post) and it generated Rust struct code which compiled correctly! Great start!
I will try to actually use it but it looks very promising, thank you!
Question: this Rust generator uses serde_derive ::Serialize and ::Deserialise instead of using serde feature = ["derive"].
What is recommended?
Should I do a global replace of lines using serde_derive:: reference to use serde:: crate for Serialize/Deserialize?
Thank you once again
serde reexports them from
serde_derive, so the only difference is that you have to add
serde_derive to your dependencies explicitly.
thank you both very much!
I have just tried using generated Rust structs and it failed because in JSON there are some fields that are not always provided i.e. in Rust terms they are Option<T>.
So just as hack, I edited the generated Rust struct to replace Type with Option<Type and it seems to have worked !!
My question is there:
let res_json2: serde_json::Result<Root = serde_json::from_str(&testjson);
Does serde_json::from_str actually support Option fields inside nested struct or was this just a lucky accident?
If Option is not supported by serde_json::from_str (or another method?) then I cannot use Rust strongly typed approach and must revert to using dynamic typed solution (as I would have to from Python, for example). It is not ideal but it is a workable plan-B for me.
serde allows one to use
Option, yes - that's not a hack,
Option is an idiomatic way to say "this value might not exist". Moreover, if you have several possible structures, you might find enum representations documentation useful, to describe the shape of your data even more strictly.
wow, this is fantastic!
Rust is great and so it's ecosystem and the user community!
It is no wonder Rust is the most loved programming languages for years running!
Including just released results for 2021, Rust is #1.
Keep it up.
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.