将JSON映射到类对象 [英] Mapping JSON into Class Objects

查看:223
本文介绍了将JSON映射到类对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将JSON文件映射到类对象中,然后根据新接收的JSON更新卡。

I am trying to map my JSON file into a class object, and then update the cards based on the newly received 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类创建的对象的字段?

How can I map the values in my JSON file into the fields of objects created from CardInfo class?

更新

以下试验打印在 ci.description 中为null,是否表示从未创建对象?

the following trial prints null at ci.description, does this mean the object was never created ?

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提供以下内容:

Printing cardInfo gives the following:


{$ class:FirstCard,id:1,description :我是卡号第一,........}

{$class: FirstCard, id: 1, description: I am card number one,........}

请注意,它类似于原始JSON,但没有双精度字符串值的引号。

Note that it resembles the original JSON but without the double quotes on string values.

推荐答案

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 为您生成序列化和反序列化代码。

You can use source generation tools like https://github.com/dart-lang/source_gen https://pub.dartlang.org/packages/json_serializable to generate the serialization and deserialization code for you.

如果您喜欢使用不可变的类,请 https://pub.dartlang.org/packages/built_value 是个好选择。

If you prefer using immutable classes https://pub.dartlang.org/packages/built_value is a good bet.

这篇关于将JSON映射到类对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆