json - 将字段映射到 fromjson dart
问题描述
这可能是一个愚蠢的问题,但我很难理解 fromJson 和 toJson 是如何工作的。
在这种情况下,如果我使用列表,我会这样做:
class DataPerDaysInfo{
List<Product>? products;
DataPerDaysInfo({required this.products});
factory DataPerDaysInfo.fromJson(Map<String, dynamic> json) => DataPerDaysInfo(
products : json["products"] == null ? null: List<Product>.from(json["products"].map((x) => Product.fromJson(x))));
Map<String, dynamic> toJson() =>
{
"products": products == null
? null
: List<dynamic>.from(products!.map((x) => x.toJson())),
};
}
但是如果我需要使用地图,我该怎么做?
class DataPerDaysInfo{
Map<String, List<Product>> mapper;
DataPerDaysInfo({required this.mapper});
}
解决方案
没有给出 json 字符串。很难猜。但也许这个实现对你有一点帮助:
import 'dart:convert';
void main() {
var dpdi = DataPerDaysInfo.fromJson(jsonDecode(json));
print(dpdi.toJson());
}
final String json = '''
{
"catalog1": [
{"id": 1, "name": "first"},
{"id": 2, "name": "second"}
],
"catalog2": [
{"id": 1, "name": "first"},
{"id": 2, "name": "second"}
]
}
''';
class DataPerDaysInfo {
Map<String, List<Product>> mapper = {};
DataPerDaysInfo.fromJson(Map<String, dynamic> json) {
json.forEach((key, value) => mapper[key] = value
.map((val) => Product.fromJson(val))
.cast<Product>()
.toList(growable: false));
}
String toJson() {
return jsonEncode(mapper);
}
}
class Product {
final int id;
final String name;
Product.fromJson(Map<String, dynamic> json)
: id = json['id'],
name = json['name'];
@override
String toString() {
return 'id: $id, name: $name';
}
Map<String, dynamic> toJson() {
return {'id': id, 'name': name};
}
}
推荐阅读
- verilog - 下一阶段的 Systemverilog 递归更新值
- arduino - ESP32 - 在一项任务中进行多任务处理
- reactjs - Gatsby 在使用 onLoad 时构建出现窗口错误
- c# - C# 并行用于减速
- c# - 如何在 wpf 应用程序中制作自定义热键并执行各种操作
- jquery - jQuery检查动画左侧是否大于1000px
- javascript - Javascript 闭包编译器
- c++ - 如何快速读取文件以检查签名/幻数?
- python - 如何使用变量来引用 Python SQLite 中的列?
- android-studio - 为什么 Android Studio 不显示小部件的可能属性?