将JSON映射到类对象

发布于 2021-01-31 16:03:10

我正在尝试将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,但在字符串值上没有双引号。

关注者
0
被浏览
137
1 个回答
  • 面试哥
    面试哥 2021-01-31
    为面试而生,有面试问题,就找面试哥。
    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是一个不错的选择。



推荐阅读
知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看