Flutter使用json_annotation反序列化报错:_InternalLinkedHashMap不兼容ItemStatus
问题
我正在使用json_annotation为自定义类ItemStatus生成fromJson和toJson方法:
import 'package:json_annotation/json_annotation.dart'; part 'item.g.dart'; @JsonSerializable(explicitToJson: true, anyMap: true) class ItemStatus { final String id; int vote = 0; bool saved = false; bool postRead = false; bool articleRead = false; ItemStatus({required this.id}); //generate using: flutter pub run build_runner build --delete-conflicting-outputs factory ItemStatus.fromJson(Map<String, dynamic> json) => _$ItemStatusFromJson(json); Map<String, dynamic> toJson() => _$ItemStatusToJson(this); }
编码过程正常,但尝试将其解码回ItemStatus类型时抛出错误:
type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'ItemStatus'
执行编码和解码的代码如下:
try { final itemStatus = ItemStatus(id: "abcd123"); itemStatus.saved = true; final jsonString = jsonEncode(itemStatus); print("jsonString: $jsonString"); ItemStatus decoded = jsonDecode(jsonString); print("decoded: $decoded"); } catch (e) { print("Error: $e"); }
请问哪里操作出错了?
解决方法
- 错误原因:
jsonDecode()函数仅会把JSON字符串解析成Map<String, dynamic>类型对象,不会自动转换为自定义的ItemStatus类实例,直接赋值给ItemStatus类型变量会触发类型不匹配错误。 - 修正方式:解析JSON字符串后,必须调用
ItemStatus.fromJson()方法,将Map对象转换为目标类实例。
修正后的解码代码:
try { final itemStatus = ItemStatus(id: "abcd123"); itemStatus.saved = true; final jsonString = jsonEncode(itemStatus); print("jsonString: $jsonString"); // 先解析成Map,再通过fromJson转成ItemStatus实例 final jsonMap = jsonDecode(jsonString) as Map<String, dynamic>; ItemStatus decoded = ItemStatus.fromJson(jsonMap); print("decoded: $decoded"); } catch (e) { print("Error: $e"); }
内容的提问来源于stack exchange,提问作者sudoExclamationExclamation
相关产品推荐
相关产品推荐

