在Dart中解析具有嵌套对象数组的JSON?

时间:2018-05-15 23:22:32

标签: json dart flutter

我正在创建一个Flutter应用程序,我正在使用The MovieDB api来获取数据。当我打电话给api并要求一部特定的电影时,这是我得到的一般格式:

{
   "adult": false,
    "backdrop_path": "/wrqUiMXttHE4UBFMhLHlN601MZh.jpg",
    "belongs_to_collection": null,
    "budget": 120000000,
    "genres": [
        {
            "id": 28,
            "name": "Action"
        },
        {
            "id": 12,
            "name": "Adventure"
        },
        {
            "id": 878,
            "name": "Science Fiction"
        }
    ],
    "homepage": "http://www.rampagethemovie.com",
    "id": 427641,
    "imdb_id": "tt2231461",
    "original_language": "en",
    "original_title": "Rampage",
...
}

我已经设置了一个模型类来解析它,并且类定义如下:

import 'dart:async';

class MovieDetail {
  final String title;
  final double rating;
  final String posterArtUrl;
  final backgroundArtUrl;
  final List<Genre> genres;
  final String overview;
  final String tagline;
  final int id;

  const MovieDetail(
      {this.title, this.rating, this.posterArtUrl, this.backgroundArtUrl, this.genres, this.overview, this.tagline, this.id});

  MovieDetail.fromJson(Map jsonMap)
      : title = jsonMap['title'],
        rating = jsonMap['vote_average'].toDouble(),
        posterArtUrl = "http://image.tmdb.org/t/p/w342" + jsonMap['backdrop_path'],
        backgroundArtUrl = "http://image.tmdb.org/t/p/w500" + jsonMap['poster_path'],
        genres = (jsonMap['genres']).map((i) => Genre.fromJson(i)).toList(),
        overview = jsonMap['overview'],
        tagline = jsonMap['tagline'],
        id = jsonMap['id'];
}
class Genre {
  final int id;
  final String genre;

  const Genre(this.id, this.genre);

  Genre.fromJson(Map jsonMap)
    : id = jsonMap['id'],
      genre = jsonMap['name'];
}

我的问题是我无法从JSON中正确解析该类型。当我获得JSON并将其传递给我的模型类时,我收到以下错误:

I/flutter (10874): type 'List<dynamic>' is not a subtype of type 'List<Genre>' where
I/flutter (10874):   List is from dart:core
I/flutter (10874):   List is from dart:core
I/flutter (10874):   Genre is from package:flutter_app_first/models/movieDetail.dart

我认为这会有效,因为我为Genre对象创建了一个不同的类,并将JSON数组作为列表传递。我不明白List<dynamic>不是List<Genre>的孩子,因为关键字dynamic暗示任何对象?有谁知道如何将嵌套的JSON数组解析为自定义对象?

4 个答案:

答案 0 :(得分:14)

尝试genres = (jsonMap['genres'] as List).map((i) => Genre.fromJson(i)).toList()

问题:在没有强制转换的情况下调用map会使其成为动态调用,这意味着来自Genre.fromJson的返回类型也是动态的(不是流派)。

请查看https://flutter.io/json/以获取一些提示。

有一些解决方案,比如https://pub.dartlang.org/packages/json_serializable,可以让这更容易

答案 1 :(得分:4)

我认为JSONtoDart Converter非常有用,必须尝试...

答案 2 :(得分:1)

首先,在收到响应后,您需要分别提取数组。然后,您可以轻松映射。这就是我的方法。

List<Attempts> attempts;
attempts=(jsonDecode(res.body)['message1'] as List).map((i) => Attempts.fromJson(i)).toList();
List<Posts> posts;
attempts=(jsonDecode(res.body)['message2'] as List).map((i) => Post.fromJson(i)).toList();

请参阅下面的示例。

   Future<List<Attempts>> getStatisticData() async {
    String uri = global.serverDNS + "PaperAttemptsManager.php";
    var res = await http.post(
      uri,
      headers: <String, String>{
        'Content-Type': 'application/json; charset=UTF-8',
      },
      body: jsonEncode(<String, String>{
        'userName': widget.userId,
        'subject': widget.subjectName,
        'method': "GETPTEN",
      }),
    );

    if (res.statusCode == 200) {
      List<Attempts> attempts;
      attempts=(jsonDecode(res.body)['message'] as List).map((i) => Attempts.fromJson(i)).toList();
      return attempts;
    } else {
      throw "Can't get subjects.";
    }
  }

模型类

class Attempts {
  String message, userName, date, year, time;
  int status, id, marks, correctAnswers, wrongAnswers, emptyAnswers;

  Attempts({
    this.status,
    this.message,
    this.id,
    this.userName,
    this.date,
    this.year,
    this.marks,
    this.time,
    this.correctAnswers,
    this.wrongAnswers,
    this.emptyAnswers,
  });

  factory Attempts.fromJson(Map<String, dynamic> json) {
    return Attempts(
      status: json['status'],
      message: json['message'],
      id: json['ID'],
      userName: json['USERNAME'],
      date: json['DATE'],
      year: json['YEAR'],
      marks: json['MARKS'],
      time: json['TIME'],
      correctAnswers: json['CORRECT_ANSWERS'],
      wrongAnswers: json['WRONG_ANSWERS'],
      emptyAnswers: json['EMPTY_ANSWERS'],
    );
  }
}

答案 3 :(得分:1)

这是一个简单易懂的示例。

将JSON字符串作为这样的嵌套对象。

{
  "title": "Dart Tutorial",
  "description": "Way to parse Json",
  "author": {
    "name": "bezkoder",
    "age": 30
  

} } 我们可以考虑以下两个类:

  • User for author
  • {title, description, author}的教程

所以我们可以像这样定义一个新的教程。

class User {
  String name;
  int age;
  ...
}

class Tutorial {
  String title;
  String description;
  User author;

  Tutorial(this.title, this.description, this.author);

  factory Tutorial.fromJson(dynamic json) {
    return Tutorial(json['title'] as String, json['description'] as String, User.fromJson(json['author']));
  }

  @override
  String toString() {
    return '{ ${this.title}, ${this.description}, ${this.author} }';
  }
}

main()函数现在看起来像下面的代码。 导入'dart:convert';

main() {
  String nestedObjText =
      '{"title": "Dart Tutorial", "description": "Way to parse Json", "author": {"name": "bezkoder", "age": 30}}';

  Tutorial tutorial = Tutorial.fromJson(jsonDecode(nestedObjText));

  print(tutorial);

检查结果,您可以看到我们的嵌套对象:

{ Dart Tutorial, Way to parse Json, { bezkoder, 30 } }

看到:Dart/Flutter parse JSON string into Nested Object