json - 当您无法控制提供的 JSON 的结构时,使用 freezed 的 Union/Sealed Classes JSON 序列化建模的最佳方法是什么?
问题描述
给定一个不可修改的 JSON,您可以像这样从服务器获得:
{ "name": "someName",
"fields": [
{ "name": "field1",
"type": "text",
"subtype": "autofill",
"value": "someVal" },
{ "name": "field2",
"type": "text",
"subtype": "password",
"value": "somePass" },
{ "name": "field3",
"type": "number",
"subtype": "integer",
"value": 12 },
{ "name": "field4",
"type": "number",
"subtype": "double",
"value": 3.14 }
],
"etc": "etc"
}
冻结的模型应该是这样的:
@freezed
class ExampleSuperclass with _$ExampleSuperclass {
factory ExampleSuperclass({
String? name,
List<Field>? fields,
String? etc,
}) = _ExampleSuperclass;
factory ExampleSuperclass.fromJson(Map<String, dynamic> json) =>
_$ExampleSuperclassFromJson(json);
}
@Freezed(unionKey: 'type')
class Field with _$Field {
factory Field({
String? name,
String? type,
String? subtype,
}) = _Field;
factory Field.text({
String? name,
String? type,
String? subtype,
}) = _FieldText;
factory Field.number({
String? name,
String? type,
String? subtype,
}) = _FieldNumber;
factory Field.fromJson(Map<String, dynamic> json) => _$FieldFromJson(json);
}
但是您意识到您需要类型和子类型才能创建更多的 Field.number 和 Field.text 子类型,您如何实现自定义 fromJson 来完成这项工作?
解决方案
推荐阅读
- c# - 如何对下拉列表数据文本字段进行 html 解码?
- debugging - 调试在 Windows 应用程序上运行的 javascript 网页
- c - FFTW 单精度库在使用 SIMD 优化时输出不正确的 DFT
- swift - 尝试对物体进行 360 度旋转
- excel - 使用 VBA 通过屏幕抓取获取自定义元素
- idl-programming-language - 如何在 IDL 编程语言中为多个图分配多个标题
- python - 无法通过 pyenv 在 Ubuntu 20.04 上降级 Python 3.4 的 sqlite3.sqlite_version 以运行 tox 测试
- git - HG-Git:AttributeError:“字节”对象没有属性“编码”
- dbase - dbf 文件(dBase 7 格式)中的时间戳字段没有意义
- u-boot - 修改 U-Boot 以依赖 mmc 中的地址而不是文件系统