我正在尝试将我的 JSON 文件映射到一个类对象,然后根据新收到的 JSON 更新卡片。
我的JSON结构是这样的
{
"$class": "FirstCard",
"id": "1",
"description": "I am card number one",
"Role": "attack",
"score": 0,
"tag": [
"string"
],................}
我的类(class)看起来像这样:
class CardInfo {
//Constructor
String id;
String description;
String role;
int score;
}
如何将 JSON 文件中的值映射到从 CardInfo 类创建的对象的字段中?
更新
以下试验在 ci.description 处打印 null,这是否意味着该对象从未创建?
const jsonCodec = const JsonCodec
_loadData() async {
var url = 'myJsonURL';
var httpClient = createHttpClient();
var response =await httpClient.get(url);
print ("response" + response.body);
Map cardInfo = jsonCodec.decode(response.body);
var ci = new CardInfo.fromJson(cardInfo);
print (ci.description); //prints null
}
更新2
打印 cardInfo 给出以下信息:
{$class: FirstCard, id: 1, description: I am card number one,........}
请注意,它类似于原始 JSON,但在字符串值上没有双引号。
最佳答案
class CardInfo {
//Constructor
String id;
String description;
String role;
int score;
CardInfo.fromJson(Map json) {
id = json['id'];
description = json['description'];
role = json['Role'];
score = json['score'];
}
}
var ci = new CardInfo.fromJson(myJson);
您可以使用源代码生成工具,例如 https://github.com/dart-lang/source_gen https://pub.dartlang.org/packages/json_serializable为您生成序列化和反序列化代码。
如果您更喜欢使用不可变类 https://pub.dartlang.org/packages/built_value是个不错的选择。
https://stackoverflow.com/questions/45189282/
相关文章:
dart - 如何使用 Flutter 检测用户在我的屏幕上点击的位置?
flutter - 没有为类 'signInWithGoogle' 定义方法 'FirebaseAu
flutter - 如何完全处理我的 Stateful Widget?
dart - Java byte[] 的 Dart 等价物是什么
android - 在无状态小部件中使用 TextFormField 在 flutter 中非常困难
file - 在 Flutter 中保存照片(尤其是到相机胶卷)
flutter - BlocProvider 在继承的小部件中不可用