问题
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
回答1:
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.
回答2:

回答3:
i recommend this article: https://medium.com/flutter-community/parsing-complex-json-in-flutter-747c46655f51
class Result
{
String id ;
String date;
String reg ;
String start;
String end ;
Result({this.date,this.end,this.id,this.reg,this.start});
factory Result.fromJson(Map<String, dynamic> parsedJson) {
return new Result(
id: parsedJson['ID'],
date: parsedJson['DATE'],
reg: parsedJson['REG'],
start: parsedJson['START'],
end: parsedJson['END'],
);
}
}
class Results
{
String total;
List<Result> results;
Results({this.results, this.total});
factory Results.fromJson(Map<String, dynamic> parsedJson) {
var list = parsedJson['results'][] as List;
return new Results(
total: parsedJson['total'],
results: list.map((i) => Result.fromJson(i)).toList());
}}
来源:https://stackoverflow.com/questions/53968769/flutter-how-to-decode-this-complex-json-string