简体   繁体   中英

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. I did try to get a parser class with quicktype.io but It seems to not work at all. Can someone please guide me or assist me with this issue? Thanks!

There is a good plugin for that in Android Studio.
JSON to Dart Class.
Once you install the plugin do as follow.

  • Press ALT + L
  • Give a Class Name and paste your JSON response
  • 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

I followed this official document of Flutter and it works for me.

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
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. It is better to give it a JSON name using JsonKey annotation.

  1. Run flutter pub run build_runner build in the terminal.
  2. stackoverflow.g.dart will be generated like this.
// 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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