将JSON映射到类对象
问题描述:
我试图将我的JSON文件映射到一个类对象,然后基于新接收的JSON更新卡片。将JSON映射到类对象
我的JSON结构是这样的
{
"$class": "FirstCard",
"id": "1",
"description": "I am card number one",
"Role": "attack",
"score": 0,
"tag": [
"string"
],................}
我的课是这样的:
class CardInfo {
//Constructor
String id;
String description;
String role;
int score;
}
我怎么能在我的JSON文件中的值映射到从CardInfo类创建的对象的字段?
更新
以下试印在ci.description空,这是否意味着该对象从未被创造出来的?
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
}
UPDATE2
印刷cardInfo给出如下:
{$类:FirstCard,ID:1,描述:我的卡号一个,...... ..}
请注意,它类似于原始的JSON,但没有字符串值的双引号。
答
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);
您可以使用源代码生成工具(如https://github.com/dart-lang/source_gen)为您生成序列化和反序列化代码。
如果您更喜欢使用不可变类https://pub.dartlang.org/packages/built_value是一个不错的选择。
答
如果你想从一个网址让你的JSON如下操作:
import 'dart:convert';
_toObject() async {
var url = 'YourJSONurl';
var httpClient = createHttpClient();
var response =await httpClient.get(url);
Map cardInfo = JSON.decode(response.body);
var ci = new CardInfo.fromJson(cardInfo);
}
请参阅主的答案,如果你想知道如何设置类,以便您的JSON字段可以被映射到它。这非常有帮助。
请检查我的文章中更新的部分,我尝试打印对象ci中的一个字段,我得到的全部为空。 – aziza
'print(cardInfo);'print? –
请在原始文章中查看我的新更新。 – aziza