【问题标题】:Parsing complex json data in Flutter在 Flutter 中解析复杂的 json 数据
【发布时间】:2020-06-08 18:49:28
【问题描述】:

我们是 Flutter 的新手。在我们的项目中,我们必须发布一个请求,它应该返回一个文本和一个附件(链接与操作,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...');
}

}

【问题讨论】:

    标签: json list parsing flutter request


    【解决方案1】:

    您的Botresp 应该定义一个List&lt;Attachment&gt; 来存储您的附件。 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&lt;Attachment&gt;。

    【讨论】:

      猜你喜欢
      • 2020-12-21
      • 2020-04-13
      • 2020-10-29
      • 2021-06-20
      • 2020-10-21
      • 2020-08-18
      • 2021-07-20
      相关资源
      最近更新 更多