跳至主要内容

JSON 转 Rust 结构体

将 JSON 转换为带 serde Serialize/Deserialize 的 Rust 结构体,支持 rename_all,可选字段使用 Option,关键字使用原始标识符。符合 rustfmt 格式。

100% 客户端 · 没有数据离开您的浏览器

skip_serializing_if on optional fields

Rust — 3 types
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Root {
    pub id: i64,
    pub username: String,
    pub email: String,
    pub is_active: bool,
    pub rating: f64,
    pub created_at: String,
    pub avatar_url: serde_json::Value,
    pub tags: Vec<String>,
    pub address: Address,
    pub orders: Vec<Order>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Address {
    pub street: String,
    pub city: String,
    pub zip_code: String,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Order {
    pub order_id: String,
    pub total: f64,
    pub items: i64,
    pub shipped: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub coupon: Option<String>,
}

Arrays of objects are merged: a key missing from some items becomes optional, null makes a field nullable, and identical shapes share one type. Paste several examples in an array for the most accurate types.

关于此工具

粘贴 JSON,即可得到能用 serde 反序列化该 JSON 的 Rust 结构体。字段使用 snake_case,工具会选择最适合您的键的 #[serde(rename_all)] 规则(camelCase、PascalCase、kebab-case……),并且只在必要时添加 #[serde(rename)]。属于 Rust 关键字的键会变成 r#type 这样的原始标识符。对象数组会被合并,因此缺失的键会变成 Option<T>(为 None 时跳过),null 也会被正确处理,整数和浮点数会被区分,嵌套对象会生成独立的结构体,以 ID 为键的对象会变成 HashMap。输出按 rustfmt 的风格格式化。您还可以在同一页面切换到 Go、C#、Python 或 Kotlin。

如何将 JSON 转换为 Rust 结构体

根据 JSON 示例生成 serde 结构体。

  1. 1

    粘贴 JSON

    粘贴一个 JSON 对象,或一个示例数组。

  2. 2

    选择选项

    设置根类型名称以及字段是否公开(pub)。

  3. 3

    复制代码

    将结构体复制到您的 crate 中;添加 serde(启用 derive feature)和 serde_json。