JSON から Rust 構造体へ
JSON を serde の Serialize/Deserialize 付き Rust 構造体に変換。rename_all、省略可能なフィールドの Option、キーワードの raw 識別子に対応し、rustfmt 準拠で出力します。
skip_serializing_if on optional fields
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 のような raw 識別子になります。オブジェクトの配列はマージされるため、欠けているキーは Option<T>(None のときはスキップ)になり、null も処理され、整数と浮動小数点数を区別し、ネストしたオブジェクトは独自の構造体になり、ID をキーにしたオブジェクトは HashMap になります。出力は rustfmt と同じ形式で整形されます。同じページから Go、C#、Python、Kotlin に切り替えることもできます。
JSON を Rust 構造体に変換する方法
JSON サンプルから serde 構造体を生成します。
- 1
JSON を貼り付け
JSON オブジェクト、または例の配列を貼り付けます。
- 2
オプションを選ぶ
ルート型の名前と、フィールドを公開(pub)にするかどうかを設定します。
- 3
コードをコピー
構造体をクレートにコピーし、serde(derive feature を有効化)と serde_json を追加します。