我正在try 将我的JSON文件映射到一个类对象,然后根据新收到的JSON更新卡.

我的JSON struct 是这样的

 {
        "$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类创建的对象的字段中?

Update

下面的试验打印空值为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提供以下信息:

{$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_genhttps://pub.dartlang.org/packages/json_serializable,为您生成序列化和反序列化代码.

如果您喜欢使用不可变的类,那么https://pub.dartlang.org/packages/built_value是个不错的 Select .

Dart相关问答推荐

基本数学函数的DART源代码

列表、捕获和...REST";元素的模式匹配

数字到字符串的转换在 Dart 中总是不变的(即没有文化)?

在 Flutter 中以间隔自动获取 API 数据

Flutter中TextFieldForm中的字母间距

Flutter drawArc() 方法绘制完整的圆而不仅仅是圆弧

Flutter:是否可以有多个 Futurebuilder 或一个 Futurebuilder 用于多个 Future 方法?

在Flutter中实现像Chanel app一样的自定义滚动?

如何在streambuilder中查询firestore文档并更新listview

Flutter - 为什么滑块不会在 AlertDialog 中更新?

Flutter Dismissible 坚持必须从树中删除列表项

如何在 Flutter 的小部件树中将新的 MaterialPageRoute 作为子项打开

了解Dart private class

Flutter:如何检测键盘按键?

如何在 Dart 中替换字符串中间的空格?

如何在dart中四舍五入?

如何突出显示所选卡片的边框?

向 javascript 公开 Dart 函数

VS Code 首选项的位置

CoffeeScript 和 Dart 对 JavaScript 的改进之间的主要区别是什么?