Biến JSON thành class Dart có factory fromJson và method toJson. Code là Dart thuần, không dùng package sinh code nào, nên không cần bước build_runner.
Nó hợp với app Flutter đang truyền thẳng Map<String, dynamic> từ response của http hay dio vào widget và muốn có class model đàng hoàng, hoặc dự án nhỏ cần serialization chạy được trước khi dùng json_serializable.
Tên kiểu (ví dụ Store).lib/models/; không cần import.Store.fromJson(jsonDecode(response.body) as Map<String, dynamic>) và gửi đi bằng 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,
};
}
Phần tử của mảng menuItems thành class MenuItem, được chuyển bên trong fromJson bằng .map(...).toList(). rating được đọc là (json['rating'] as num).toDouble() nên giá trị nguyên vẫn an toàn, còn spicy, chỉ có ở một số món, là int? và không có required trong constructor.
final; constructor dùng named parameter ({required this.x}).factory X.fromJson(Map<String, dynamic> json) và Map<String, dynamic> toJson() viết tay, không phụ thuộc package nào.fromJson / toJson của class con.double được đọc qua (as num).toDouble(), nên số nguyên JSON như 4 không gây lỗi cast.null thành nullable (int?) và truyền nguyên null trong fromJson.dynamic; từ khóa của Dart như class hay is được thêm dấu gạch dưới ở cuối.typedef Root = List<RootItem>;.Truyền Map qua FutureBuilder hay state Riverpod/Bloc sẽ giấu lỗi gõ sai key cho tới lúc runtime. Với class được tạo, bạn có gợi ý code và kiểm tra kiểu trên store.menuItems.first.price.
Lưu jsonEncode(store.toJson()) vào shared_preferences hoặc file và khôi phục bằng fromJson khi khởi động, có ngay cache chỉ với vài dòng.
Xác nhận danh sách field và kiểu trước; khi dự án lớn lên, thêm @JsonSerializable() vào chính các field đó và chuyển sang sinh code.
5000.0 thành số nguyên 5000. jsonDecode của Dart giữ 5000.0 là double, nên as int sẽ ném lỗi. Hãy đổi các field giá tiền hay tọa độ có thể mang dấu thập phân thành double.toJson ghi cả field nullable kể cả khi chúng là null ('spicy': null). Nếu server từ chối key null, hãy bỏ chúng ra có điều kiện.String; tự chuyển bằng DateTime.parse(json['createdAt'] as String).copyWith, ==/hashCode hay toString. Cân nhắc freezed hoặc equatable nếu bạn cần.dynamic giữ giá trị mà không kiểm tra; hãy thay khi đã biết kiểu thật.Output là fromJson/toJson kiểu viết tay, không dùng package. Lấy phần khai báo field, thêm @JsonSerializable() và part 'store.g.dart';, rồi chạy dart run build_runner build để chuyển sang sinh code.
type 'int' is not a subtype of type 'double'.Lỗi này xảy ra khi code cast bằng as double mà giá trị JSON là số nguyên. Field double được tạo dùng (as num).toDouble() để tránh; hãy áp dụng cùng mẫu đó cho field bạn đã sửa tay.
[ {...}, {...} ]) thế nào?Mảng ở cấp cao nhất cho ra một typedef và class phần tử. Gọi fromJson cho từng phần tử: (jsonDecode(body) as List<dynamic>).map((e) => RootItem.fromJson(e as Map<String, dynamic>)).toList().
Output dùng cú pháp sound null safety (int?, required) từ Dart 2.12 trở đi. Dự án trước null safety cần bỏ ? và required mới compile được.