Answer#
Add the crates serde (with the derive feature) and serde_json, derive Serialize and Deserialize on your types, and call serde_json::from_str. A document of the wrong shape returns an Err you handle at the edge of the program, where TypeScript would hand you a value that only looks typed.
| TypeScript | Rust with serde |
|---|---|
interface User { id: number; name: string } | struct User { id: u64, name: String } |
email?: string | email: Option<String> (add skip_serializing_if to omit it when writing) |
role: "admin" | "member" | enum Role { Admin, Member } with rename_all = "lowercase" |
{ type: "click"; x: number } | { type: "key"; key: string } | enum with #[serde(tag = "type")] |
displayName in JSON, display_name in code | #[serde(rename_all = "camelCase")] |
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
struct User {
id: u64,
name: String,
#[serde(skip_serializing_if = "Option::is_none")]
email: Option<String>,
role: Role,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
enum Role {
Admin,
Member,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "lowercase")]
enum Event {
Click { x: i32, y: i32 },
Key { key: String },
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct Profile {
display_name: String, // JSON key: "displayName"
}
fn main() -> Result<(), serde_json::Error> {
let u: User = serde_json::from_str(r#"{"id": 7, "name": "Ada", "role": "admin"}"#)?;
println!("{u:?}");
println!("{}", serde_json::to_string(&u)?);
let events: Vec<Event> = serde_json::from_str(r#"[{"type":"click","x":1,"y":2},{"type":"key","key":"Enter"}]"#)?;
println!("{events:?}");
println!("{}", serde_json::to_string(&events[0])?);
let p: Profile = serde_json::from_str(r#"{"displayName": "Ada L."}"#)?;
println!("{}", p.display_name);
let bad = serde_json::from_str::<User>(r#"{"id": "seven", "name": "Ada", "role": "owner"}"#);
println!("{}", bad.unwrap_err());
Ok(())
}User { id: 7, name: "Ada", email: None, role: Admin }
{"id":7,"name":"Ada","role":"admin"}
[Click { x: 1, y: 2 }, Key { key: "Enter" }]
{"type":"click","x":1,"y":2}
Ada L.
invalid type: string "seven", expected u64 at line 1 column 14Common mistakes#
- Using
f64for every number. Pick the integer type that matches the data; the error above is the point of the check. - Making every field
Optionto avoid parse errors. That moves the check to every place the field is used. - Forgetting
#[serde(default)]on fields that older files do not have.
Related questions#
How do I accept JSON with fields I do not know?#
Unknown fields are ignored by default. Add #[serde(deny_unknown_fields)] to reject them, or a serde_json::Value field to keep them.
Can I share the types with a TypeScript front end?#
Crates that generate TypeScript types from Rust structs exist; check that the one you choose is maintained and matches your serde attributes.
Sources#
- serde documentation: https://serde.rs/
- Container attributes: https://serde.rs/container-attrs.html