แปลง JSON เป็นคลาส Dart ที่มี factory fromJson และเมธอด toJson โค้ดเป็น Dart ล้วนโดยไม่ใช้แพ็กเกจ code generation จึงไม่ต้องมีขั้นตอน build_runner
เหมาะกับแอป Flutter ที่ส่ง response แบบ Map<String, dynamic> ดิบ ๆ จาก http หรือ dio เข้าวิดเจ็ตโดยตรงและอยากได้คลาสโมเดลจริงจัง หรือโปรเจกต์เล็กที่ต้องการ serialization ที่ใช้ได้ก่อนจะนำ json_serializable มาใช้
ชื่อไทป์ (เช่น Store)lib/models/ ไม่ต้อง import อะไรเพิ่มStore.fromJson(jsonDecode(response.body) as Map<String, dynamic>) และส่งออกด้วย jsonEncode(store.toJson()){
"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 }
]
}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 errornull จะเป็น nullable (int?) และส่ง null ผ่านไปใน fromJsondynamic และคำสงวนของ Dart อย่าง class หรือ is จะได้ขีดล่างต่อท้ายtypedef Root = List<RootItem>;การส่ง Map ผ่าน FutureBuilder หรือ state ของ Riverpod/Bloc ทำให้คีย์ที่พิมพ์ผิดซ่อนอยู่จนถึงตอนรัน แต่เมื่อใช้คลาสที่สร้างขึ้นจะได้ autocomplete และการเช็กไทป์บน store.menuItems.first.price
เก็บ jsonEncode(store.toJson()) ไว้ใน shared_preferences หรือไฟล์ แล้วกู้คืนด้วย fromJson ตอนเปิดแอป ได้แคชในไม่กี่บรรทัด
ยืนยันรายการฟิลด์และไทป์ก่อน เมื่อโปรเจกต์โตขึ้นค่อยเพิ่ม @JsonSerializable() ให้ฟิลด์ชุดเดิมแล้วย้ายไปใช้ code generation
5000.0 เป็นจำนวนเต็ม 5000 แต่ jsonDecode ของ Dart เก็บ 5000.0 เป็น double ทำให้ as int โยน exception ฟิลด์ราคาหรือพิกัดที่อาจมีจุดทศนิยมควรเปลี่ยนเป็น doubletoJson เขียนฟิลด์ nullable ออกไปแม้ค่าเป็น null ('spicy': null) ถ้าเซิร์ฟเวอร์ไม่รับคีย์ที่เป็น null ให้ตัดออกแบบมีเงื่อนไขString ให้แปลงเองด้วย DateTime.parse(json['createdAt'] as String)copyWith, ==/hashCode หรือ toString ถ้าต้องการลองพิจารณา freezed หรือ equatabledynamic เก็บค่าโดยไม่มีการเช็กไทป์ ควรเปลี่ยนเมื่อรู้ไทป์จริงแล้วผลลัพธ์เป็น 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() เพื่อเลี่ยงปัญหานี้ ให้ใช้รูปแบบเดียวกันกับฟิลด์ที่คุณแก้เอง
[ {...}, {...} ]) อย่างไร?อาร์เรย์ระดับบนสุดได้ typedef และคลาสของสมาชิก ให้เรียก fromJson ทีละสมาชิก: (jsonDecode(body) as List<dynamic>).map((e) => RootItem.fromJson(e as Map<String, dynamic>)).toList()
ผลลัพธ์ใช้ไวยากรณ์ sound null safety (int?, required) ตั้งแต่ Dart 2.12 ขึ้นไป โปรเจกต์ก่อนยุค null safety ต้องลบ ? และ required ออกจึงจะคอมไพล์ได้