小编典典

将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上 打印为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,但在字符串值上没有双引号。


阅读 289

收藏
2020-07-27

共1个答案

小编典典

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是一个不错的选择。

2020-07-27