JSON 轉 Dart 產生器

JSON 輸入

正在載入編輯器…

生成的 Dart

Configuration

輸入 JSON 資料以產生 Dart 類別

具備 null safety 與 JSON 序列化的類別

如何將 JSON 轉換為 Dart – 步驟指南

使用此 JSON 轉 Dart 產生器,可從 JSON 範例產生支援 null safety 的 Dart class,適合 Flutter 與 Dart 服務。

  1. 步驟 1 – 貼上 JSON 範例

    • 將具有代表性的 JSON 物件或陣列貼到左側編輯器。
    • 盡量包含巢狀物件、陣列與可為 null 的欄位,方便正確推斷型別。
    • 使用 匯入 從檔案、URL 或示例資料載入 JSON。
  2. 步驟 2 – 選擇 Dart class 選項

    • 為根模型設定 Class Name(例如 Root)。
    • 啟用 null safety 並確認可選欄位對應(例如 String?)。
    • 若使用程式碼產生,選擇序列化風格(例如 json_serializable)。
  3. 步驟 3 – 檢查產生的程式碼

    • 確認欄位命名、型別推斷,以及陣列/物件的對應方式是否符合預期。
    • 依需求調整 根型別名稱、null 處理策略與可選的框架選項。
    • 若某些欄位推斷不準確,優化 JSON 範例後重新產生。
  4. 步驟 4 – 在 Flutter/Dart 中使用模型

    • 將產生的 class 加入專案(例如放在 lib/models)。
    • 透過 fromJson factory 或產生的序列化程式解析 JSON。
    • 執行 flutter format 以保持程式碼風格一致。
  5. 步驟 5 – 複製或下載

    • 將輸出複製到專案中,或下載成檔案。
    • 執行格式化/程式碼檢查工具,讓風格與專案一致。
    • 若目標語言需要序列化/解析函式庫,請在專案中加入相依套件。

快速提示

  • 用巢狀型別表達結構,避免單一模型過度肥大。
  • 只有在 API 時間格式穩定時才轉成 DateTime
  • 大型模型建議使用產生的序列化器,降低手寫 mapping 錯誤。
範例輸出(簡化)
// JSON 輸入
{
  "id": 123,
  "name": "Maeve Winters",
  "email": "[email protected]",
  "active": true,
  "roles": ["admin", "editor"],
  "metadata": { "plan": "pro" },
  "createdAt": "2024-03-01T10:15:00Z",
  "score": 99.5,
  "notes": null
}

// 產生的 Dart 模型(簡化)
class Metadata {
  final String plan;
  const Metadata({required this.plan});
}

class Root {
  final int id;
  final String name;
  final String? email;
  final bool active;
  final List<String> roles;
  final Metadata metadata;
  final String createdAt;
  final double score;
  final Object? notes;

  const Root({
    required this.id,
    required this.name,
    required this.email,
    required this.active,
    required this.roles,
    required this.metadata,
    required this.createdAt,
    required this.score,
    required this.notes,
  });
}

相關 JSON 與 Dart 工具

探索更多可與本 JSON 轉 Dart 產生器搭配使用的 JSON 與 Schema 工具。

常見問題

支援哪些 Dart 特性?

產生器會建立具備型別安全的 Dart 類別,支援手動 JSON 序列化與 json_annotation 套件,使用可為 null 型別處理 null 值,並遵循 Dart 命名慣例。

json_annotation 如何運作?

選擇 json_annotation 框架時,產生的類別會使用 @JsonSerializable() 註解,並透過 build_runner 自動產生 fromJson/toJson 方法,提供型別安全的 JSON 序列化。

null 值如何處理?

JSON 中的 null 值會對應到 Dart 的可為 null 型別(?),提供 null safety。必填欄位會在建構子使用 'required',符合 Dart 的 null safety 原則。

Dart 的型別系統呢?

產生的程式碼會善用 Dart 的強型別系統,使用適當型別(int、double、String、bool、List、Map),並遵循欄位命名使用 camelCase 等慣例。

JSON 轉 Dart 產生器 | JSONSwiss