Json_Annotation 无法正确处理嵌套类

问题描述 投票:0回答:1

我有嵌套类 InventoryResult 和 Item,我想用 json 文件读取/写入它们,并且 json_annotation 生成的代码不会映射 toJson() 方法中的 Item 列表;奇怪的处理对于 fromJson() 方法来说是完全没问题的。 以下是我的两堂课:

@JsonSerializable()
class InventoryResult {
  List<Item> results;
  int number;
  int offset;
  int totalResults;

  InventoryResult({required this.results, required this.number, required this.offset, required this.totalResults});
  factory InventoryResult.fromJson(Map<String, dynamic> json) => _$InventoryResultFromJson(json);
  Map<String, dynamic> toJson() => _$InventoryResultToJson(this);

}

@JsonSerializable()
class Item {
  int id;
  String productName;

  Item(
      {required this.id,
      required this.productName});

  factory Item.fromJson(Map<String, dynamic> json) => _$ItemFromJson(json);
  Map<String, dynamic> toJson() => _$ItemToJson(this);
}

并且 Inventory 生成的 fromJson() 和 toJson() 方法有奇怪的不同:

InventoryResult _$InventoryResultFromJson(Map<String, dynamic> json) =>
    InventoryResult(
      results: (json['results'] as List<dynamic>)
          .map((e) => Item.fromJson(e as Map<String, dynamic>))
          .toList(),
      number: (json['number'] as num).toInt(),
      offset: (json['offset'] as num).toInt(),
      totalResults: (json['totalResults'] as num).toInt(),
    );

Map<String, dynamic> _$InventoryResultToJson(InventoryResult instance) =>
    <String, dynamic>{
      'results': instance.results, //INCORRECT NESTED CLASS HANDLING HERE
      'number': instance.number,
      'offset': instance.offset,
      'totalResults': instance.totalResults,
    };

自然地,当我从 Json 读取时,一切都是正确的,当我写入 json 时,它只是写入“实例”,而不是正确解析 Item 对象。我有 json_annotation 和 json_serialized 也是最新的并且完全被难住了。是否与我后来在项目中添加了 Item 的 toJson() 方法有关?之后我重新构建了很多次,也尝试完全删除生成的 g.dart 文件。两个类文件相互导入,并导入 json_annotation 包和 g.dart 文件。使用 fromJson() 和 toJson() 方法,项目生成的 g.dart 文件显示正确。我找不到问题。

android json flutter dart flutter-dependencies
1个回答
0
投票

在外部类的

explicitToJson: true
注解中添加
@JsonSerializable
标志
InventoryResult
:

@JsonSerializable(explicitToJson: true)
class InventoryResult {
  // Your existing class fields and methods
}

这确保生成的

toJson
方法将在
toJson
等嵌套对象上显式调用
Item

现在,生成的

_$InventoryResultToJson
方法将如下所示:

Map<String, dynamic> _$InventoryResultToJson(InventoryResult instance) =>
    <String, dynamic>{
      'results': instance.results.map((e) => e.toJson()).toList(), // Correctly serializes each Item
      'number': instance.number,
      'offset': instance.offset,
      'totalResults': instance.totalResults,
    };
© www.soinside.com 2019 - 2024. All rights reserved.