How to Convert Between Data Formats in Rust

Convert data between Rust structs and formats like JSON using the serde crate and its derive macros.

Use the serde crate with serde_json to serialize and deserialize data between formats like JSON and Rust structs. Add serde and serde_json to your Cargo.toml, derive Serialize and Deserialize on your struct, then use serde_json::to_string and serde_json::from_str to convert.

use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize)]
struct Data { value: i32 }

let d = Data { value: 42 };
let json = serde_json::to_string(&d).unwrap();
let parsed: Data = serde_json::from_str(&json).unwrap();