rustHow to generate struct from json in Rust
Generating struct from json in Rust is possible using the serde
crate. serde
is a powerful library for serializing and deserializing data structures.
Example code
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
struct Person {
name: String,
age: u8,
phones: Vec<String>,
}
fn main() {
// Some JSON input data as a &str. Maybe this comes from the user.
let data = r#"
{
"name": "John Doe",
"age": 43,
"phones": [
"+44 1234567",
"+44 2345678"
]
}"#;
// Parse the string of data into a Person object. This is exactly the
// same function as the one that produced serde_json::Value above, but
// now we are asking it for a Person as output.
let p: Person = serde_json::from_str(data).unwrap();
// Do things just like with any other Rust data structure.
println!("Please call {} at the number {}", p.name, p.phones[0]);
}
Output example
Please call John Doe at the number +44 1234567
Code explanation
-
use serde::{Deserialize, Serialize};
- This imports theDeserialize
andSerialize
traits from theserde
crate. These traits are used to define how a struct should be serialized and deserialized. -
#[derive(Serialize, Deserialize)]
- This is a Rust attribute that tells the compiler to generate code for theSerialize
andDeserialize
traits for thePerson
struct. -
let data = r#" ... "#;
- This is a raw string literal that contains the JSON data. -
let p: Person = serde_json::from_str(data).unwrap();
- This is the line that actually deserializes the JSON data into aPerson
struct.
Helpful links
Related
- Example of struct of structs in Rust
- Example of constant struct in Rust
- Example of struct private field in Rust
- How to init zero struct in Rust
- Example of Rust struct with closure
- How to update struct in Rust
- Rust struct without fields
- How to convert struct to bytes in Rust
- How to compare structs in Rust
- How to clone struct in Rust
More of Rust
- How to perform matrix operations in Rust?
- How to replace a capture group using Rust regex?
- How to replace all using regex in Rust?
- How to use regex to match a double quote in Rust?
- How to parse JSON string in Rust?
- How to get an entry from a HashSet in Rust?
- How to implement PartialEq for a Rust HashMap?
- How to get the length of a Rust HashMap?
- How to use an enum in a Rust HashMap?
- How to convert a Rust slice of u8 to a string?
See more codes...