当前位置: 首页 > 知识库问答 >
问题:

_InternalLinkedHashMap”不是类型转换中“List”类型的子类型

干高歌
2023-03-14

我有错误从标题时试图这样做

>

{
  "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": {
      ...
    }
  }
}

我创建了@JsonSerialiazable()类来处理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)时,当它试图从我的响应中执行(json['a']as List)时,它会给出一个错误。g、 构建运行程序生成的dart文件。

    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(),

我如何修复错误?

谢啦

共有2个答案

沈英勋
2023-03-14

您的abc字段被键入为列表,但JSON在该位置没有列表,只有一个值(作为映射)。

所以,检查您是否确实希望字段是列表,或者它们是否应该只是元素类型的单个值。

仇浩旷
2023-03-14

我在@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);
    }
 类似资料: