JSON with serde_json
Use case
You need to read and write JSON: API payloads, config files, or any structured data. The serde_json crate with serde gives type-safe serialization and deserialization.
In C#: Like System.Text.Json or Newtonsoft: serialize/deserialize to and from classes. In Rust, derive Serialize/Deserialize and use serde_json::from_str/to_string.
Deserializing JSON
Define a struct with Deserialize (and optionally Serialize). Use serde_json::from_str for a string or serde_json::from_reader for a file/stream.
use serde::Deserialize;
#[derive(Deserialize)]
struct User {
id: i32,
name: String,
email: Option<String>,
}
let json = r#"{"id": 1, "name": "Alice", "email": "alice@example.com"}"#;
let user: User = serde_json::from_str(json)?;In C#: Like JsonSerializer.Deserialize<User>(json). Use Option<T> for nullable fields.
Serializing to JSON
Derive Serialize and use serde_json::to_string or serde_json::to_writer.
use serde::Serialize;
#[derive(Serialize)]
struct Response {
status: String,
count: u32,
}
let res = Response { status: "ok".into(), count: 42 };
let json = serde_json::to_string(&res)?;In C#: Like JsonSerializer.Serialize(res).
Value and arbitrary JSON
When the structure is dynamic, use serde_json::Value: Value::Object, Value::Array, Value::String, etc. Parse with serde_json::from_str::<Value>(s)? and index or match on the value.
In C#: Like JsonElement or JObject/JArray in Newtonsoft.
Key takeaway
Use serde_json::from_str/to_string with structs that derive Serialize/Deserialize. Use serde_json::Value for dynamic JSON. All operations return Result; use ? or handle errors.