【问题标题】:Convert JSON string into list of object in Dart将 JSON 字符串转换为 Dart 中的对象列表
【发布时间】:2020-05-16 18:06:12
【问题描述】:

我正在尝试将 字符串 转换为 dart 中的对象列表。字符串如下所示:

What it looks like in my app - image

The JSON return - pastebin

我的班级模型:

class Post {
  GetDataResult getDataResult;

  Post({this.getDataResult});

  Post.fromJson(Map<String, dynamic> json) {
    getDataResult = json['GetDataResult'] != null
        ? new GetDataResult.fromJson(json['GetDataResult'])
        : null;
  }

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

class GetDataResult {
  String retVal;

  GetDataResult({this.retVal});

  GetDataResult.fromJson(Map<String, dynamic> json) {
    retVal = json['RetVal'];
  }

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

谁能帮帮我?

【问题讨论】:

  • 您可以将您的 json 数组转换为对象列表,例如 click here

标签: json string flutter serialization dart


【解决方案1】:

我解决了。首先我创建一个新的类模型:

class Profesi {
  String id;
  String description;
  String idPekerjaan;

  Profesi({this.id, this.description, this.idPekerjaan});

  Profesi from ({object: Map}) {
    var map = object;
    return Profesi(
      id: map['ID'] as String,
      description: map['Description'] as String,
      idPekerjaan: map['IDPekerjaan'] as String,
    );
  }
}

在我的 postRequest 方法中,我准备了一个变量来包含从我的 retVal 解码的 json:

List listJsonContent;
listJsonContent = json.decode(Post.fromJson(json.decode(response.body)).getDataResult.retVal);

准备一个我的新 Profesi 类的列表并使用 add() 方法插入对象(这里我只插入一个:listJsonContent[0],您可以通过迭代列表来插入全部):

List<Profesi> profesi = List<Profesi>();
profesi.add(Profesi().from(object: listJsonContent[0]));

尝试打印检查:

print('${profesi[0].id}, ${profesi[0].idPekerjaan}, ${profesi[0].description}');

【讨论】:

    【解决方案2】:

    将 Json 转换为字符串。 例如,

    类示例{字符串名称} 打印(sample.name.toString());

    【讨论】:

      【解决方案3】:

      使用此链接从 Json 创建 Dart 对象。

      访问https://javiercbk.github.io/json_to_dart/这个!

      【讨论】:

      • 没有。我需要从 JSON 对象转换字符串值。我已经制作了班级模型。
      【解决方案4】:

      你需要使用gson,将你的字符串转换成对象列表,gson.fromJson()方法返回你想要的json格式:

      SomeObject[] yourJson = gson.fromJson(jsonObject.toString(), SomeObject[].class);
      

      请尝试以上可以,如果您仍然遇到问题分享您的错误。

      【讨论】:

        猜你喜欢
        • 2018-05-01
        • 2015-02-28
        • 1970-01-01
        • 2021-01-06
        • 2014-04-07
        • 2021-04-14
        • 1970-01-01
        • 2021-08-01
        相关资源
        最近更新 更多