简体   繁体   English

在 Flutter 中解析复杂 json 时出现问题

[英]Problems parsing complex json in Flutter

I am having issues converting the following 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
   }
 ]
}

I tried using the jsonserializer plugin as well as the json_annotations plugin but got nowhere.我尝试使用 jsonserializer 插件以及 json_annotations 插件,但一无所获。 I did try to get a parser class with quicktype.io but It seems to not work at all.我确实尝试使用 quicktype.io 获得解析器 class 但它似乎根本不起作用。 Can someone please guide me or assist me with this issue?有人可以指导我或帮助我解决这个问题吗? Thanks!谢谢!

There is a good plugin for that in Android Studio. Android Studio 中有一个很好的插件。
JSON to Dart Class. JSON 至 Dart Class。
Once you install the plugin do as follow.安装插件后,请执行以下操作。

  • Press ALT + L按 ALT + L
  • Give a Class Name and paste your JSON response给出 Class 名称并粘贴您的 JSON 响应
  • And you are done.你完成了。

在此处输入图像描述

After you get a response do as follow as收到回复后,请执行以下操作

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

If you need the status code of you response then response.statusCode如果您需要响应的状态代码,那么response.statusCode

I followed this official document of Flutter and it works for me.我遵循了 Flutter 的官方文档,它对我有用。

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

Follow these steps to solve your problem.请按照以下步骤解决您的问题。

  1. Add dependencies as shown in the document.添加依赖项,如文档中所示。
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. Create stackoverflow.dart创建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);
}

Giving variable name as _id will confuse Dart with a private variable.将变量名称指定为_id会将 Dart 与私有变量混淆。 It is better to give it a JSON name using JsonKey annotation.最好使用 JsonKey 注释给它一个 JSON 名称。

  1. Run flutter pub run build_runner build in the terminal.在终端中运行flutter pub run build_runner build
  2. stackoverflow.g.dart will be generated like this. 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. For testing do this为了测试这样做
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);

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

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