我有一些類,我可以使用 flutter jsonEncode/jsonDecode 宏很好地序列化:
part 'friend.g.dart';
@JsonSerializable(explicitToJson: true)
class Friend {
Friend({required this.name});
@JsonKey(required: true)
late String name;
@JsonKey(required: true)
late final Preferences prefTree;
@JsonKey(required: false, defaultValue: "assets/avatars/cat.png")
late String avatarAsset = avatarAssets[Random().nextInt(avatarAssets.length-1)];
factory Friend.fromJson(Map<String, dynamic> json) => _$FriendFromJson(json);
Map<String, dynamic> toJson() => _$FriendToJson(this);
Map<String, dynamic> _$FriendToJson(Friend instance) => <String, dynamic>{
'name': instance.name,
'avatarAsset': instance.avatarAsset,
'isFavorite': instance.isFavorite,
'prefTree': instance.prefTree,
};
....
}
它作業得非常好,并且在反序列化時,如果 json 檔案中不存在 JSON 值,它將使用默認值。
問題是序列化器。
我想要的是
- 當我的類屬性具有默認值時,并且
- 該屬性不是必需的,并且
- 我的實體的屬性值與默認值相同,
==> 那么序列化程式不會在 json 檔案中記下該值。這將為我節省 JSON 檔案中的數十萬行。
我閱讀了不同的 JSON 成員,如“required”、“defaultValue”等,我使用了它們,但序列化程式似乎仍然沒有考慮到這一點。再一次,解串器的作用就像一個魅力。因此,不要將我的類序列化為:
{
"itemName": "Brown",
"itemIconString": "",
"isAPreference": false
},
我想讓它像這樣序列化(因為默認值):
{
"itemName": "Brown",
},
是我還是無法避免在 jsonEncode 中輸出成員的默認值?
謝謝!
uj5u.com熱心網友回復:
我不認為 JsonSerializable 提供這樣的選項。但你可以手動撰寫。
這是一個例子:
class Test {
final int a; // default is 1
final int b; // default is 2
Test({ this.a = 1, this.b = 2});
Map<String, dynamic> toJson() {
final result = <String, dynamic>{};
if (a != 1) {
result['a'] = a;
}
if (b != 2) {
result['b'] = b;
}
return result;
}
}
void main() {
final t = Test(a: 1, b: 1);
print(t.toJson());
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/385800.html
上一篇:當我無法控制源字串時,如何在JavaScript中將字串化陣列轉換為陣列?
下一篇:Javascript中的陣列轉換
