我在做这个的时候有一个标题上的错误
我有这种类型的JSON,其中第一个参数是唯一的键

{
  "3dfb71719a11693760f91f26f4f79c3c": {
    "a": {
      "var1": {
        "value": "8678468,4,2,2,0,0",
        "time": 1544536734000
      },
      "var2": {
        "value": "8678468,4,2,2,0,0",
        "time": 1544536734000
      },
      ...
    },
    "b": {
      "var3": {
        "value": "8678468,4,2,2,0,0",
        "time": 1544536734000
      },
      ...
    },
    "c": {
      "var4": {
        "value": "8678468,4,2,2,0,0",
        "time": 1544536734000
      },
      ...
    }
  },
  "c91891522a8016fc8a097b9e405b118a": {
    "a": {
      ...
    },
    "b": {
      ...
    },
    "c": {
      ...
    }
  }
}

我创建了@jsonseriazable()类来处理json
@JsonSeriazable()
class MyResponse {
  final List<AType> a;
  final List<BType> b;
  final List<Ctype> c;

  MyResponse(this.a, this.b, this.c);

  factory MyResponse.fromJson(Map<String, dynamic> json) => _$MyResponseFromJson(json);
}

class AType {
    final StringValueTime var1;
    final StringValueTime var2;
    ...

    AType(this.var1, this.var2, ...);

    factory AType.fromJson(Map<String, dynamic> json) => $_ATypeFromJson(json);
}

然后,在调用http.get()时,我会这样做:
Map<String, dynamic> map = json.decode(response.body);
List<MyResponse> myObjects = List<MyResponse>();

final keys = map.keys;

keys.forEach((id) {
  final MyResponse obj = MyResponse.fromJson(map[id]);
  myOjects.add(obj);
});

map变量如下所示:
    0: "3dfb71719a11693760f91f26f4f79c3c"
        key: "3dfb71719a11693760f91f26f4f79c3c"
        value: <Map (3 items)>
          0: "a" <Map x items>
             key: "a"
             value: <Map x items>
          1: "b" <Map x items>
          2: "c" <Map x items>
    1: "c91891522a8016fc8a097b9e405b118a"

当调用$myResponseFromJSON(JSON)时,它会在尝试从构建运行程序生成的\u response.g.dart文件执行(JSON['A']作为列表)时给出错误。
    MyResponse _$MyResponseFromJson(Map<String, dynamic> json) {
      return MyResponse(
          (json['a'] as List)
              ?.map((e) =>
                  e == null ? null : AType.fromJson(e as Map<String, dynamic>))
              ?.toList(),

如何修复错误?
谢谢

最佳答案

我在@irn的帮助下发现了我的问题。这个班应该是这样的

    @JsonSeriazable()
    class MyResponse {
      final AType a;
      final BType b;
      final Ctype c;

      MyResponse(this.a, this.b, this.c);

      factory MyResponse.fromJson(Map<String, dynamic> json) => _$MyResponseFromJson(json);
    }

    class AType {
        final StringValueTime var1;
        final StringValueTime var2;
        ...

        AType(this.var1, this.var2, ...);

        factory AType.fromJson(Map<String, dynamic> json) => $_ATypeFromJson(json);
    }

关于dart - _InternalLinkedHashMap <String,dynamic>'不是类型转换中类型'List <dynamic>'的子类型,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54412644/

10-12 17:38
查看更多