rustHow to convert struct to JSON string in Rust?
Converting a struct to a JSON string in Rust can be done using the serde
crate. serde
provides a set of macros to serialize and deserialize data structures to and from JSON.
Example code
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize)]
struct Person {
name: String,
age: u8,
}
fn main() {
let person = Person {
name: "John".to_string(),
age: 30,
};
let json_string = serde_json::to_string(&person).unwrap();
println!("{}", json_string);
}
Output example
{"name":"John","age":30}
Code explanation
use serde::{Serialize, Deserialize};
: imports theSerialize
andDeserialize
traits from theserde
crate.#[derive(Serialize, Deserialize)]
: derives theSerialize
andDeserialize
traits for thePerson
struct.serde_json::to_string(&person).unwrap()
: serializes theperson
struct to a JSON string.
Helpful links
Related
More of Rust
- How to match a URL with a regex in Rust?
- How to replace a capture group using Rust regex?
- How to replace strings using Rust regex?
- How to match whitespace with a regex in Rust?
- How to split a string with Rust regex?
- Regex example to match multiline string in Rust?
- How to use regex lookahead in Rust?
- How to get a capture group using Rust regex?
- How to use regex builder in Rust?
- How to check if a regex is valid in Rust?
See more codes...