【问题标题】:Iterate a Json parsed http response in flutter在颤动中迭代一个 Json 解析的 http 响应
【发布时间】:2020-11-27 02:24:17
【问题描述】:

我收到一个 http 响应。然后我解析它。
我的问题是如何在 for 循环中迭代 json 解析响应

     final response =
     await http.get('http://10.0.2.2:8080/api/getetab');
     if (response.statusCode == 200) {
       var parsedJson = json.decode(response.body);
       print(parsedJson) ;

       return parsedJson ;
     } else {
       throw Exception('Failed to load');
     }

这是 parsedJson 打印结果:

[{id: 1, nom: violette, adresse: tunis, categorie: coiffeuse, createdAt: 2020-08-05T12:10:10.000Z, updatedAt: 2020-08-05T12:10:10.000Z}, {id: 2, nom: soho, adresse: ariena, categorie: coiffeuse, createdAt: 2020-08-05T12:10:10.000Z, updatedAt: 2020-08-05T12:10:10.000Z}]

如何在 for 循环中迭代 'parsedJson'?

【问题讨论】:

  • 在这之后你到底想做什么,我的意思是,还有其他更简单的选择。
  • 我只想将 parsedJson 迭代到一个 for 循环中,但我找不到 parsedJson.length
  • 你能发布一下 json 的样子吗?然后我们可以帮助您。
  • @NiklasLehnfeld 请查看我添加了 parsedjson 的打印结果的帖子

标签: flutter dart


【解决方案1】:
  1. 我假设您错过了 json 中的引号。应该看起来像:
"[{\"id\": 1, \"nom\": \"violette\", \"adresse\": \"tunis\", \"categorie\": \"coiffeuse\", \"createdAt\": \"2020-08-05T12:10:10.000Z\", \"updatedAt\": \"2020-08-05T12:10:10.000Z\"}, {\"id\": 2, \"nom\": \"soho\", \"adresse\": \"ariena\", \"categorie\": \"coiffeuse\", \"createdAt\": \"2020-08-05T12:10:10.000Z\", \"updatedAt\": \"2020-08-05T12:10:10.000Z\"}]";
  1. 当您将上面的这个 json 放入 json.decode(String) 方法中时,它会返回一个 List<Map<String, dynamic>>。您可以使用简单的forEach-Loop 对其进行迭代。
String jsonString =
        "[{\"id\": 1, \"nom\": \"violette\", \"adresse\": \"tunis\", \"categorie\": \"coiffeuse\", \"createdAt\": \"2020-08-05T12:10:10.000Z\", \"updatedAt\": \"2020-08-05T12:10:10.000Z\"}, {\"id\": 2, \"nom\": \"soho\", \"adresse\": \"ariena\", \"categorie\": \"coiffeuse\", \"createdAt\": \"2020-08-05T12:10:10.000Z\", \"updatedAt\": \"2020-08-05T12:10:10.000Z\"}]";
    

List<dynamic> data = json.decode(jsonString);

data.forEach((entry) {
  int id = entry["id"];
  String nom = entry["nom"];
  String adresse = entry["adresse"];

  print("id: $id, nom: $nom, adresse: $adresse");
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-13
    • 1970-01-01
    • 1970-01-01
    • 2019-08-31
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多