Day 13k: Serialization and Deserialization of Vectors
Introduction
Serialization and deserialization are important when working with data formats like JSON. Rust’s serde
library allows you to easily serialize and deserialize vectors. In this session, we’ll cover how to convert vectors to and from JSON.
Serializing a Vector to JSON
To serialize a vector into JSON, you can use the serde_json
crate. Here’s an example:
use serde_json::json;
fn main() {
let numbers = vec![1, 2, 3, 4, 5];
let json = serde_json::to_string(&numbers).unwrap();
println!("{}", json); // Output: [1,2,3,4,5]
}
Deserializing JSON to a Vector
To deserialize JSON back into a vector, use serde_json::from_str()
:
use serde_json::json;
fn main() {
let data = "[1, 2, 3, 4, 5]";
let numbers: Vec<i32> = serde_json::from_str(data).unwrap();
println!("{:?}", numbers); // Output: [1, 2, 3, 4, 5]
}
Conclusion
Serialization and deserialization allow you to convert vectors into formats like JSON for storage or transmission. With the help of the serde
library, these conversions become straightforward.