我正在尝试将JSON文件映射到类对象,然后根据新接收的JSON更新卡。
我的JSON结构是这样的
{
"$class": "FirstCard",
"id": "1",
"description": "I am card number one",
"Role": "attack",
"score": 0,
"tag": [
"string"
],................}
Run Code Online (Sandbox Code Playgroud)
我的班级看起来像这样:
class CardInfo {
//Constructor
String id;
String description;
String role;
int score;
}
Run Code Online (Sandbox Code Playgroud)
如何将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
}
Run Code Online (Sandbox Code Playgroud)
更新2
打印cardInfo给出以下内容:
{$ class:FirstCard,id:1,说明:我是第一卡,........}
请注意,它类似于原始的JSON,但在字符串值上没有双引号。
Gün*_*uer 11
class CardInfo {
//Constructor
String id;
String description;
String role;
int score;
CardInfo.fromJson(Map json) {
this.id = json['id'];
this.description = json['description'];
this.role = json['Role'];
this.score = json['score'];
}
}
var ci = new CardInfo.fromJson(myJson);
Run Code Online (Sandbox Code Playgroud)
您可以使用源生成工具,例如https://github.com/dart-lang/source_gen https://pub.dartlang.org/packages/json_serializable来为您生成序列化和反序列化代码。
如果您更喜欢使用不可变的类,那么https://pub.dartlang.org/packages/built_value是一个不错的选择。
| 归档时间: |
|
| 查看次数: |
6800 次 |
| 最近记录: |