首页 > 解决方案 > 当您无法控制提供的 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 来完成这项工作?

标签: jsondeserializationflutter-freezed

解决方案


推荐阅读