แปลง JSON เป็น class ของ Dart!

ป้อน JSON เพื่อสร้างโค้ด class ของ Dart รวมถึงออบเจ็กต์ที่ซ้อนกัน! รองรับ Flutter, fromJson, toJson
JSON
ผลลัพธ์
 

แปลง JSON เป็น class ของ Dart!

แปลง JSON เป็นคลาส Dart ที่มี factory fromJson และเมธอด toJson โค้ดเป็น Dart ล้วนโดยไม่ใช้แพ็กเกจ code generation จึงไม่ต้องมีขั้นตอน build_runner

เหมาะกับแอป Flutter ที่ส่ง response แบบ Map<String, dynamic> ดิบ ๆ จาก http หรือ dio เข้าวิดเจ็ตโดยตรงและอยากได้คลาสโมเดลจริงจัง หรือโปรเจกต์เล็กที่ต้องการ serialization ที่ใช้ได้ก่อนจะนำ json_serializable มาใช้

วิธีใช้

  1. วาง JSON ที่ต้องการแปลง
  2. ใส่ชื่อคลาสระดับบนสุดใน ชื่อไทป์ (เช่น Store)
  3. วางผลลัพธ์ลงในไฟล์ใต้ lib/models/ ไม่ต้อง import อะไรเพิ่ม
  4. สร้างออบเจ็กต์ด้วย Store.fromJson(jsonDecode(response.body) as Map<String, dynamic>) และส่งออกด้วย jsonEncode(store.toJson())

ตัวอย่าง

อินพุต (JSON)
{
  "storeId": 77,
  "storeName": "Mapo Kimbap",
  "isOpen": true,
  "rating": 4.7,
  "menuItems": [
    { "name": "Tuna Kimbap", "price": 4500, "soldOut": false },
    { "name": "Ramyeon", "price": 5000, "soldOut": true, "spicy": 2 }
  ]
}
เอาต์พุต (Dart)
class Store {
  final int storeId;
  final String storeName;
  final bool isOpen;
  final double rating;
  final List<MenuItem> menuItems;

  Store({
    required this.storeId,
    required this.storeName,
    required this.isOpen,
    required this.rating,
    required this.menuItems,
  });

  factory Store.fromJson(Map<String, dynamic> json) => Store(
        storeId: json['storeId'] as int,
        storeName: json['storeName'] as String,
        isOpen: json['isOpen'] as bool,
        rating: (json['rating'] as num).toDouble(),
        menuItems: (json['menuItems'] as List<dynamic>).map((e) => MenuItem.fromJson(e as Map<String, dynamic>)).toList(),
      );

  Map<String, dynamic> toJson() => {
        'storeId': storeId,
        'storeName': storeName,
        'isOpen': isOpen,
        'rating': rating,
        'menuItems': menuItems.map((e) => e.toJson()).toList(),
      };
}

class MenuItem {
  final String name;
  final int price;
  final bool soldOut;
  final int? spicy;

  MenuItem({
    required this.name,
    required this.price,
    required this.soldOut,
    this.spicy,
  });

  factory MenuItem.fromJson(Map<String, dynamic> json) => MenuItem(
        name: json['name'] as String,
        price: json['price'] as int,
        soldOut: json['soldOut'] as bool,
        spicy: json['spicy'] as int?,
      );

  Map<String, dynamic> toJson() => {
        'name': name,
        'price': price,
        'soldOut': soldOut,
        'spicy': spicy,
      };
}

สมาชิกของอาร์เรย์ menuItems กลายเป็นคลาส MenuItem และถูกแปลงใน fromJson ด้วย .map(...).toList() rating ถูกอ่านเป็น (json['rating'] as num).toDouble() ค่าที่เป็นจำนวนเต็มจึงยังปลอดภัย ส่วน spicy ที่มีแค่ในบางเมนูเป็น int? และไม่มี required ใน constructor

ฟีเจอร์ที่รองรับ

  • ทุกฟิลด์เป็น final และ constructor ใช้ named parameter ({required this.x})
  • factory X.fromJson(Map<String, dynamic> json) และ Map<String, dynamic> toJson() แบบเขียนมือ ไม่พึ่งแพ็กเกจใด
  • ออบเจ็กต์ซ้อนและอาร์เรย์ของออบเจ็กต์เรียก fromJson / toJson ของคลาสลูก
  • ฟิลด์ double อ่านผ่าน (as num).toDouble() จำนวนเต็มใน JSON อย่าง 4 จึงไม่ทำให้เกิด cast error
  • ฟิลด์ที่ขาดไปในบางรายการหรือมีค่า null จะเป็น nullable (int?) และส่ง null ผ่านไปใน fromJson
  • ค่าที่ไทป์ปนกันเป็น dynamic และคำสงวนของ Dart อย่าง class หรือ is จะได้ขีดล่างต่อท้าย
  • อาร์เรย์ระดับบนสุดได้ typedef Root = List<RootItem>;

กรณีการใช้งาน

โมเดล API สำหรับหน้าจอ Flutter

การส่ง Map ผ่าน FutureBuilder หรือ state ของ Riverpod/Bloc ทำให้คีย์ที่พิมพ์ผิดซ่อนอยู่จนถึงตอนรัน แต่เมื่อใช้คลาสที่สร้างขึ้นจะได้ autocomplete และการเช็กไทป์บน store.menuItems.first.price

แคชในเครื่อง

เก็บ jsonEncode(store.toJson()) ไว้ใน shared_preferences หรือไฟล์ แล้วกู้คืนด้วย fromJson ตอนเปิดแอป ได้แคชในไม่กี่บรรทัด

ร่างแรกก่อนใช้ json_serializable

ยืนยันรายการฟิลด์และไทป์ก่อน เมื่อโปรเจกต์โตขึ้นค่อยเพิ่ม @JsonSerializable() ให้ฟิลด์ชุดเดิมแล้วย้ายไปใช้ code generation

ข้อควรระวังและข้อจำกัด

  • ไทป์ถูกอนุมานด้วย JSON parser ของเบราว์เซอร์ ซึ่งอ่าน 5000.0 เป็นจำนวนเต็ม 5000 แต่ jsonDecode ของ Dart เก็บ 5000.0 เป็น double ทำให้ as int โยน exception ฟิลด์ราคาหรือพิกัดที่อาจมีจุดทศนิยมควรเปลี่ยนเป็น double
  • toJson เขียนฟิลด์ nullable ออกไปแม้ค่าเป็น null ('spicy': null) ถ้าเซิร์ฟเวอร์ไม่รับคีย์ที่เป็น null ให้ตัดออกแบบมีเงื่อนไข
  • สตริงวันที่ยังเป็น String ให้แปลงเองด้วย DateTime.parse(json['createdAt'] as String)
  • ไม่สร้าง copyWith, ==/hashCode หรือ toString ถ้าต้องการลองพิจารณา freezed หรือ equatable
  • ฟิลด์ dynamic เก็บค่าโดยไม่มีการเช็กไทป์ ควรเปลี่ยนเมื่อรู้ไทป์จริงแล้ว

คำถามที่พบบ่อย

สร้างโค้ด json_serializable หรือ freezed ได้ไหม?

ผลลัพธ์เป็น fromJson/toJson สไตล์เขียนมือที่ไม่ใช้แพ็กเกจ ให้นำการประกาศฟิลด์ไปเพิ่ม @JsonSerializable() และ part 'store.g.dart'; แล้วรัน dart run build_runner build เพื่อเปลี่ยนไปใช้ code generation

เจอ type 'int' is not a subtype of type 'double'

เกิดขึ้นเมื่อโค้ด cast ด้วย as double แต่ค่าใน JSON เป็นจำนวนเต็ม ฟิลด์ double ที่สร้างขึ้นใช้ (as num).toDouble() เพื่อเลี่ยงปัญหานี้ ให้ใช้รูปแบบเดียวกันกับฟิลด์ที่คุณแก้เอง

จะ decode response ที่เป็นลิสต์ ([ {...}, {...} ]) อย่างไร?

อาร์เรย์ระดับบนสุดได้ typedef และคลาสของสมาชิก ให้เรียก fromJson ทีละสมาชิก: (jsonDecode(body) as List<dynamic>).map((e) => RootItem.fromJson(e as Map<String, dynamic>)).toList()

ใช้กับโปรเจกต์เก่าที่ยังไม่มี null safety ได้ไหม?

ผลลัพธ์ใช้ไวยากรณ์ sound null safety (int?, required) ตั้งแต่ Dart 2.12 ขึ้นไป โปรเจกต์ก่อนยุค null safety ต้องลบ ? และ required ออกจึงจะคอมไพล์ได้