Flutter:如何解码此复杂的JSON字符串 [英] Flutter: how to decode this complex JSON string

查看:400
本文介绍了Flutter:如何解码此复杂的JSON字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从我的REST API中以

的形式接收JSON字符串

{总计":"30",结果":[ {"ID":"1809221034017","DATE":"2018-09-22","REG":(E9)","START":"10:40","END":"10:48" }, {"ID":"1809221337250","DATE":"2018-09-22","REG":(E4)","START":"13:43","END":"13:57" }, {"ID":"1809161032213","DATE":"2018-09-16","REG":(E1)","START":"11:04","END":"11:13" }]}

total字段告诉我该数据库总共包含30条记录,结果部分包括了所请求的数据(仅3行).

我需要解析数据,以便可以在ListView中显示结果.我设法用一个简单的JSON字符串来做到这一点,但是没有使用这个复杂的JSON字符串来做到这一点.不幸的是,我无法更改Web服务的输出,因为它是由第三方托管的.

感谢任何帮助或代码示例.

预先感谢

解决方案

请先阅读我的 quicktype 的类生成库.

例如,使用快速类型,您可以使用JSON轻松,自动地在dart中生成moidel类. 在此生成文件.

quicktype --lang dart --all-properties-optional https://www.shadowsheep.it/so/53968769/testjson.php -o my_json_class.dart

然后在代码中使用它:

import 'my_json_class.dart';
import 'package:http/http.dart' as http;

var response = await http.get('https://www.shadowsheep.it/so/53968769/testjson.php');
    var myClass = MyJsonClass.fromJson(jsonDecode(response.body));
    for(var result in myClass.results.toList()) {
       print(result?.id);
    }

NB 如果您将掌握一个代码生成器库,那么您将能够解析来自REST API的任何类型的JSON,您将有更多的时间来玩乐. /p>

From my REST API a JSON string is received as

{"total":"30","results":[ {"ID":"1809221034017","DATE":"2018-09-22","REG":"(E9)","START":"10:40","END":"10:48"}, {"ID":"1809221337250","DATE":"2018-09-22","REG":"(E4)","START":"13:43","END":"13:57"}, {"ID":"1809161032213","DATE":"2018-09-16","REG":"(E1)","START":"11:04","END":"11:13"}]}

The total field tells me that the database contains in total 30 records, the requested data (only 3 rows) is included in the results section.

I need to parse the data, so I can show the results in ListView. I managed to do this with a simple JSON string, but not with this complex JSON string. Unfortunately I am not able to change the output of the web service since this is hosted by a 3rd party.

Any help, or a code example, is appreciated.

Thanks in advance

解决方案

Read first my other answer here.

Then I suggest you to use a class generation library like quicktype.

Using quick type for example you can easily and automatically genearate your moidel class in dart using your JSON. Here the generated file.

quicktype --lang dart --all-properties-optional https://www.shadowsheep.it/so/53968769/testjson.php -o my_json_class.dart

Then use it in code:

import 'my_json_class.dart';
import 'package:http/http.dart' as http;

var response = await http.get('https://www.shadowsheep.it/so/53968769/testjson.php');
    var myClass = MyJsonClass.fromJson(jsonDecode(response.body));
    for(var result in myClass.results.toList()) {
       print(result?.id);
    }

N.B. If you'll master a code generator library, then you'll be able to parse any type of JSON coming from a REST API and you'll have more time for fun.

这篇关于Flutter:如何解码此复杂的JSON字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆