rustHow to serialize JSON in Rust?
Serializing JSON in Rust is done using the serde
crate. serde
provides a powerful framework for serializing and deserializing data structures.
Example code
extern crate serde;
extern crate serde_json;
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 serialized = serde_json::to_string(&person).unwrap();
println!("serialized = {}", serialized);
}
Output example
serialized = {"name":"John","age":30}
Code explanation
extern crate serde;
andextern crate serde_json;
: imports theserde
andserde_json
crates.#[derive(Serialize, Deserialize)]
: derives theSerialize
andDeserialize
traits for thePerson
struct.serde_json::to_string(&person).unwrap()
: serializes theperson
struct into a JSON string.
Helpful links
Related
More of Rust
- How to replace a capture group using Rust regex?
- How to match the end of a line in a Rust regex?
- How to use regex with bytes in Rust?
- How to use regex to match a double quote in Rust?
- How to check if a regex is valid in Rust?
- How to get a value by key from JSON in Rust?
- How to implement PartialEq for a Rust HashMap?
- How to insert an element into a Rust HashMap if it does not already exist?
- How to convert a Rust slice of u8 to a string?
- How to extract data with regex in Rust?
See more codes...