【问题标题】:How to convert JSON to object in Flutter? [closed]如何在 Flutter 中将 JSON 转换为对象? [关闭]
【发布时间】:2020-11-23 20:23:20
【问题描述】:
{
    "mon" : {
        "a" : 3,
        "b" : 2,
        "c" : 4
    }
    "tue" : {
        "a" : 3,
        "b" : 2,
        "c" : 4
    }
    "wed" : {
        "a" : 3,
        "b" : 2,
        "c" : 4
    }
    ...
    "sun" : {
        "a" : 1,
        "b" : 2,
        "c" : 3
    }
}

字段名称相同这是重复字段值
这是一种仅更改键的结构。
你如何序列化这种类型的 JSON?
我想制作一个对象并将其浮动在我的 UI

周一、周二、周三、...周日,我真的需要创建一个课程吗?

我想轻松导入和写入一周中每一天的数据

【问题讨论】:

  • 这个问题需要澄清一下。你到底在做什么?
  • 你想基于这个 JSON 或者你真正想要的东西来创建模型文件
  • @Vasanth Vadivel 你是对的

标签: flutter dart flutter-layout


【解决方案1】:

也许,这个网站就是你要找的: https://javiercbk.github.io/json_to_dart/

您只需粘贴您的 json(通常是来自 API 的响应),它就会在 dart 中为该 json 创建一个类。那么,你可以像这样使用它:

MyJsonClass classResponse = MyJsonClass.fromJson(apiResponse);

并像这样访问它的参数:

print(classResponse.mon.a) // output: 3

使用的生成代码:

class Days {
  Mon mon;
  Mon tue;
  Mon wed;
  Mon sun;

  Days({this.mon, this.tue, this.wed, this.sun});

  Days.fromJson(Map<String, dynamic> json) {
    mon = json['mon'] != null ? new Mon.fromJson(json['mon']) : null;
    tue = json['tue'] != null ? new Mon.fromJson(json['tue']) : null;
    wed = json['wed'] != null ? new Mon.fromJson(json['wed']) : null;
    sun = json['sun'] != null ? new Mon.fromJson(json['sun']) : null;
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    if (this.mon != null) {
      data['mon'] = this.mon.toJson();
    }
    if (this.tue != null) {
      data['tue'] = this.tue.toJson();
    }
    if (this.wed != null) {
      data['wed'] = this.wed.toJson();
    }
    if (this.sun != null) {
      data['sun'] = this.sun.toJson();
    }
    return data;
  }
}

class Mon {
  int a;
  int b;
  int c;

  Mon({this.a, this.b, this.c});

  Mon.fromJson(Map<String, dynamic> json) {
    a = json['a'];
    b = json['b'];
    c = json['c'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['a'] = this.a;
    data['b'] = this.b;
    data['c'] = this.c;
    return data;
  }
}

【讨论】:

  • 使用该网站,您需要为一周中的每一天创建一个课程。那么代码是不是太乱了?有什么办法吗?
  • 实际上并不是每天都创建一个类。在我的例子中,它正在创建一个 Mon 类的实例。我用从那里生成的代码更新了我的答案。
  • 感谢您对一个不好的问题给出一个好的答案
猜你喜欢
  • 2019-03-30
  • 2015-08-03
  • 1970-01-01
  • 1970-01-01
  • 2013-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多