【问题标题】:How to convert _JsonMap to object in flutter / dart如何将_JsonMap转换为flutter / dart中的对象
【发布时间】:2021-12-18 17:10:44
【问题描述】:

我有以下课程:

@JsonSerializable(explicitToJson: true)
class Section {
  @JsonKey(name: '_id')
  late String id;
  late BaseInfo info;
  @JsonKey(name: 'document_ids')
  late List<String>? documentIds;
  late List<String>? tags;
  late List<Comment>? comments;
  late List<UserBasedPermission>? permissions;

  Section();

  factory Section.fromJson(Map<String, dynamic> json) =>
      _$SectionFromJson(json);

  Map<String, dynamic> toJson() => _$SectionToJson(this);
}

现在,当我尝试调用 fromJson 时,我收到一条错误消息,提示应该是 Map&lt;String, dynamic&gt;,但找到了 _JsonMap。 我用来转换的代码如下:

String test = '{"_id":"610b8ce9faa3695a81b93e98","info":{"name":"Mathematik","description":"Alles was mit Mathe zu tun hat Hurz ein Reh. Ein Hirsch 222 3333 444 555","active":false,"created_date":1628146903325,"created_by":"admin","last_update":null,"last_update_by":null,"last_comment":null,"deletion_date":null,"deleted_by":null,"locked_by":null,"locked_date":null,"object_type":"SECTION","version":6,"api_version":1},"document_ids":[],"tags":["mathematik","mathe","wissenschaft"],"comments":[{"user":"","timestamp":1628579634126,"comment":"Das ist ein Kommentar"},{"user":"admin","timestamp":1628580529698,"comment":"Noch ein Kommentar"}],"permissions":{"read_write_users":null,"read_only_users":null,"excluded_users":null}}';
        Map<String, dynamic> parsedJson = jsonDecode(test);
        print("parsedJson type: ${parsedJson.runtimeType} / $parsedJson");
        Section sec = Section.fromJson(parsedJson);

我就是不知道问题出在哪里。

【问题讨论】:

  • Section.fromJson(Map&lt;String, dynamic&gt;.from(parsedJson));时有什么变化吗?
  • 不,很遗憾,错误还是一样

标签: json flutter dart


【解决方案1】:

尝试以这种方式创建变量:

 Map<String, dynamic> parsedJson = jsonDecode(test) as Map<String,dynamic>;

【讨论】:

  • 不幸的是,这没有帮助。我仍然收到错误“预期类型为 'List?' 的值?”但得到了“_JsonMap”之一
  • 错误到底在哪一行?
  • 这里出现错误Section sec = Section.fromJson(parsedJson);
  • print 行之前的输出工作正常:parsedJson type: _JsonMap / {_id: 610b8ce9faa3695a81b93e98, info: {name: Mathematik, description: Alles ...
  • 试试这个Section.fromJson(parsedJson as Map&lt;String,dynamic&gt;);
【解决方案2】:

显然 JsonSerializable 注解存在一些问题。在我将其更改为 @JsonSerializable(explicitToJson: true, includeIfNull: true, anyMap: false) 后,它按预期工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-30
    • 2022-01-08
    • 2022-11-17
    • 2018-12-13
    • 1970-01-01
    • 2021-08-05
    • 2020-11-05
    • 2020-07-03
    相关资源
    最近更新 更多