在Flutter中解析复杂的json时遇到问题

时间:2020-07-01 13:24:20

标签: arrays json flutter dart response

我在转换以下响应时遇到问题->

{
"data": [
{
  "_id": "1AoJoWJ5Hdx3nZ5t",
  "title": "Orange is the new black",
  "imageUrl": "/1532353304050-oinb.jpg",
  "likesCount": 674
 },
{
  "_id": "AeqiQJewtTvMPc1B",
  "title": "X-Files",
  "imageUrl": "/1532353346638-xfiles.png",
  "likesCount": 6155
 },
{
  "_id": "gPkzfXoJXX5TuTuM",
  "title": "Star Trek: Voyager",
  "imageUrl": "/1532353336145-voyager.jpg",
  "likesCount": 23
 },
{
  "_id": "vQBQcYwtF9GWWJyK",
  "title": "South Park",
  "imageUrl": "/1532353313669-southpark.jpg",
  "likesCount": 56
 },
{
  "_id": "wjLUixBQ4sirMAYw",
  "title": "The Simpsons",
  "imageUrl": "/1532353326075-thesimpsons.jpg",
  "likesCount": 65
   }
 ]
}

我尝试使用jsonserializer插件以及json_annotations插件,但无济于事。 我确实尝试使用quicktype.io获取一个解析器类,但它似乎根本不起作用。 有人可以指导我或协助我解决这个问题吗? 谢谢!

2 个答案:

答案 0 :(得分:1)

Android Studio中有一个很好的插件。
JSON转换为Dart类。
安装插件后,请执行以下操作。

  • 按ALT + L
  • 提供一个类名并粘贴您的JSON响应
  • 您完成了。

enter image description here

得到回应后,请按照以下步骤操作

import 'dart:convert';
var decodedData = json.decode(response.body);
var data = Data.fromJson(decodedData)

如果您需要响应的状态码,则response.statusCode

答案 1 :(得分:1)

我遵循了Flutter的这份正式文件,并且对我有用。

https://flutter.dev/docs/development/data-and-backend/json

请按照以下步骤解决您的问题。

  1. 添加依赖项,如文档所示。
dependencies:
  # Your other regular dependencies here
  json_annotation: <latest_version>

dev_dependencies:
  # Your other dev_dependencies here
  build_runner: <latest_version>
  json_serializable: <latest_version>

  1. 创建stackoverflow.dart
import 'package:json_annotation/json_annotation.dart';

part 'stackoverflow.g.dart';

@JsonSerializable()
class StackOverFlowModel {
  @JsonKey(name: '_id')
  String id;
  String title;
  String imageUrl;
  int likesCount;

  StackOverFlowModel();
  
  factory StackOverFlowModel.fromJson(Map<String, dynamic> json) =>
      _$StackOverFlowModelFromJson(json);
  Map<String, dynamic> toJson() => _$StackOverFlowModelToJson(this);
}

将变量名设为_id会使Dart与私有变量混淆。最好使用JsonKey批注为其指定JSON名称。

  1. 在终端中运行flutter pub run build_runner build
  2. stackoverflow.g.dart将会这样生成。
// GENERATED CODE - DO NOT MODIFY BY HAND

part of 'stackoverflow.dart';

// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************

StackOverFlowModel _$StackOverFlowModelFromJson(Map<String, dynamic> json) {
  return StackOverFlowModel()
    ..id = json['_id'] as String
    ..title = json['title'] as String
    ..imageUrl = json['imageUrl'] as String
    ..likesCount = json['likesCount'] as int;
}

Map<String, dynamic> _$StackOverFlowModelToJson(StackOverFlowModel instance) =>
    <String, dynamic>{
      '_id': instance.id,
      'title': instance.title,
      'imageUrl': instance.imageUrl,
      'likesCount': instance.likesCount
    };

  1. 进行测试
Map map = {
    "data": [
      {
        "_id": "1AoJoWJ5Hdx3nZ5t",
        "title": "Orange is the new black",
        "imageUrl": "/1532353304050-oinb.jpg",
        "likesCount": 674
      },
      {
        "_id": "AeqiQJewtTvMPc1B",
        "title": "X-Files",
        "imageUrl": "/1532353346638-xfiles.png",
        "likesCount": 6155
      },
      {
        "_id": "gPkzfXoJXX5TuTuM",
        "title": "Star Trek: Voyager",
        "imageUrl": "/1532353336145-voyager.jpg",
        "likesCount": 23
      },
      {
        "_id": "vQBQcYwtF9GWWJyK",
        "title": "South Park",
        "imageUrl": "/1532353313669-southpark.jpg",
        "likesCount": 56
      },
      {
        "_id": "wjLUixBQ4sirMAYw",
        "title": "The Simpsons",
        "imageUrl": "/1532353326075-thesimpsons.jpg",
        "likesCount": 65
      }
    ]
  };

  List<StackOverFlowModel> list = List.generate(map['data'].length,
      (index) => StackOverFlowModel.fromJson(map['data'][index]));

  print(list);