简体   繁体   English

Flutter - Json.decode返回错误的json

[英]Flutter - Json.decode return incorrect json

Recently I change all JSON of my app to show the errors, messages, and body of the service. 最近我更改了我的应用程序的所有JSON,以显示服务的错误,消息和正文。 In the body, I have an array of data. 在正文中,我有一系列数据。 Before I change the JSON, all worked doing something like this: 在我更改JSON之前,所有人都在做这样的事情:

final responseJson = json.decode(response.body);

Which returned: 返回的是:

[{"id":1,"descripcion":"Terreno Rio"},{"id":2,"descripcion":"Terreno Asier"}] [{“id”:1,“descripcion”:“Terreno Rio”},{“id”:2,“descripcion”:“Terreno Asier”}]

Now I try to do something like this: 现在我尝试做这样的事情:

final responseJson = json.decode(response.body);
print(json.encode(responseJson));

Which returns: 哪个回报:

[{"code":0,"message":"","body":[{"id":1,"descripcion":"Terreno Rio"},{"id":2,"descripcion":"Terreno Asier"}]}] [{“code”:0,“message”:“”,“body”:[{“id”:1,“descripcion”:“Terreno Rio”},{“id”:2,“descripcion”:“Terreno Asier“}]}]

Does anybody know the right way to extract some element of the JSON and decode? 有人知道提取JSON的一些元素并解码的正确方法吗?

I'm sure the JSON response that you get is like this: 我确定你得到的JSON响应是这样的:

{"code":0,"message":"","body":[{"id":1,"descripcion":"Terreno Rio"},{"id":2,"descripcion":"Terreno Asier"}]} {“code”:0,“message”:“”,“body”:[{“id”:1,“descripcion”:“Terreno Rio”},{“id”:2,“descripcion”:“Terreno Asier “}]}

So in order to parse that JSON, you can just access the body directly: 因此,为了解析该JSON,您可以直接访问正文:

List list = responseJson['body'];

Now you can iterate through the elements of the array: 现在您可以遍历数组的元素:

for (Map<String, dynamic> element in list) {
    print(element);
}

You get a List of Maps . 你会得到一张Maps List First access the first element (there is only 1) of the List with [0] and then the body element of the returned Map with ['body'] : 首先使用[0] List的第一个元素(只有1个),然后使用['body']返回的Mapbody元素:

var body = responseJson[0]['body'];
print(body);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM