反复抖动Json解析的http响应

时间:2020-08-06 18:57:19

标签: flutter dart

我收到一个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”?

1 个答案:

答案 0 :(得分:0)

  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");
});