【问题标题】:Access nested objects in json using json_serializable in Dart在 Dart 中使用 json_serializable 访问 json 中的嵌套对象
【发布时间】:2020-08-15 06:12:17
【问题描述】:

尝试使用 json_serializable 将我的 json 转换为 Dart/Flutter 中的对象。我似乎找不到访问嵌套 ID 的方法(数据来自 MongoDB,因此 json 中的 $)。

这是json:

{
    "_id": {
        "$oid": "5c00b227"  <-- this is what I am trying to access 
    },
    "base": 1,
    "tax": 1,
    "minimum": 5,
    "type": "blah"
}

结果:

class Thing {
  final int id;
  final String base;
  final String tax;
  final String type;
  final int minimum;
}

【问题讨论】:

    标签: json flutter dart


    【解决方案1】:

    试试这个,

    class Thing {
       int id;
       String base;
       String tax;
       String type;
       int minimum;
    
       Thing({
        this.id,
        this.base,
        this.tax,
        this.type,
        this.minimum,
      });
    
       factory Thing.fromJson(Map<String, dynamic> json) {
         return Thing(
           id: json['_id']["oid"],
           base: json['base'].toString(),
           tax: json['tax'].toString(),
           type: json['type'].toString(),
           minimum: json['minimum'],
         );
       }
    }
    

    【讨论】:

    • 有没有办法在 jsons/thing.json 文件中使用 JsonKey(name: 'id') final String "id" (但在嵌套 json 上使用它)?如果我在运行 json_model 时使用您的代码,如果 json 发生变化,那么它将覆盖工厂方法。如果我从原始 json 中的“id”中删除“”,那么它可以工作。我猜 json_model 不喜欢“”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多