在Flutter中解析复杂的json数据

时间:2020-06-08 18:49:28

标签: json list parsing flutter request

我们是Flutter的新手。在我们项目的某一点上,我们必须发布一个请求,它应该返回一个文本和一个附件(如果有的话,链接为action,fett kursiv ...),因为文本效果很好,但是附件却没有t,下面写的附件是一个列表。我们如何也能获得对附件的响应?谢谢。

身体反应:

[
{
    "requestText": null,
    "text": "Hey, what kann I do for you?",
    "accessToken": null,
    "attachments": [{          {
            "name": "",
            "type": "LINK",
            "filename": "",
            "job": "",
            "title": "transfer to Yahoo",
            "action": "Zu Google",
            "video": null,
            "link": "https://www.yahoo.com",
            "accordionText": "",
            "datePickerRange": "",
            "mediaType": null,
            "multipleChoiceOptions": null
        },],
    "action": null,
    "activeBot": null,
  #  "messageKey": null,
    "error": false
}

]

我们的工作代码,但仅适用于文本:

  Future<Botresp> createAlbum(String text) async {

final http.Response response1 = await http.post(
  '(private Link....)',
  headers: <String, String>{
    'Content-Type': 'application/json; charset=UTF-8',
    'historyID' : 'dsdsadsadasdasddsds',
    'username':  'test',
  },
  body: jsonEncode({
    "text": '${text}' ,
  }),
);
final jsonresponse = json.decode(response1.body);
if (response1.statusCode == 200) {
  print(jsonresponse[0]);
  return Botresp.fromJson(jsonresponse[0]);
} else {
  throw Exception('Failed to create...');
}

}

1 个答案:

答案 0 :(得分:0)

您的Botresp应该定义一个List<Attachment>来存储您的附件。 Attachment类如下所示:

class Attachment {
  String name;
  // add the rest of the fields here

  Attachment({this.name});

  factory Attachment.fromJson(Map<String, dynamic> json) {
    return Attachment(
      name: json['name'] as String,
    );
  }

  static List<Attachment> fromJsonList(List json) {
    List<Attachment> attachments =
        json.map((attachment) => Attachment.fromJson(attachment)).toList();
    return attachments;
  }
}

然后在您的Botresp.fromJson中使用Attachment.fromJsonList将其解析为您的List<Attachment>