rustHow to convert JSON to a struct in Rust?
JSON can be converted to a struct in Rust using the serde
crate. The serde
crate provides a Deserialize
trait which can be used to convert JSON data into a Rust struct.
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. -
#[derive(Serialize, Deserialize)]
: This is a Rust attribute which tells the compiler to generate code for theSerialize
andDeserialize
traits for thePerson
struct. -
let p: Person = serde_json::from_str(data).unwrap();
: This line uses theserde_json::from_str
function to parse the JSON data into aPerson
struct.
Helpful links
Related
More of Rust
- Hashshet example in Rust
- How to use a tuple as a key in a Rust HashMap?
- How to get a capture group using Rust regex?
- How to split a string with Rust regex?
- How to replace strings using Rust regex?
- How to parse a file with Rust regex?
- How to use regex to match a group in Rust?
- How to parse JSON string in Rust?
- How to get an entry from a HashSet in Rust?
- How to convert a Rust HashMap to a JSON string?
See more codes...