将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上 打印为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,说明:我是第一卡,....}
请注意,它类似于原始的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/json_serializable为您生成序列化和反序列化代码。如果您更喜欢使用不可变的类,那么https://pub.dartlang.org/packages/built_value是一个不错的选择。
-
将JSON对象映射到Hibernate实体
2021-02-01 关注 0 浏览135 1答案
-
将JSON数据映射到Java对象
2021-01-30 关注 0 浏览109 1答案
-
如何使用JPA将映射JSON列映射到Java对象
2021-02-02 关注 0 浏览99 1答案
-
如何将JSON映射到C#对象
2021-01-31 关注 0 浏览137 1答案
-
将json映射到Java对象的最佳方法
2021-01-30 关注 0 浏览83 1答案
-
将字符串映射到json对象的多种类型?
2021-02-01 关注 0 浏览123 1答案
-
如何将JSON映射到Java模型类
2021-01-30 关注 0 浏览87 1答案
-
将HTML映射到JSON
2021-02-02 关注 0 浏览79 1答案
-
将JPA实体的JSON字符串列自动映射到Java对象
2021-01-31 关注 0 浏览229 1答案
-
使用Jersey / JAXB / Jackson将Java.util.Map映射到JSON对象
2021-01-31 关注 0 浏览74 1答案