在 angulardart 教程中,您无法找到有关如何从比示例更复杂的 json 中获取数据的信息

in the angulardart tutorial, you can't find information on how to get data from a more complex json than in the example

在 angulardart 教程中,您无法找到有关如何从比示例更复杂的 json 中获取数据的信息 link to the tutorial

json 在 brauser django rest 框架中

Content-Type: application/vnd.api+json
Vary: Accept

{
    "data": [
        {
            "type": "Hero",
            "id": "1",
            "**attributes**": {
                "name": "Windstorm"
            }
        },
        {
            "type": "Hero",
            "id": "2",
            "**attributes**": {
                "name": "Bombasto"
            }
        },
        {
            "type": "Hero",
            "id": "3",
            "**attributes**": {
                "name": "Magneta"
            }
        },
        {
            "type": "Hero",
            "id": "4",
            "**attributes**": {
                "name": "Tornado"
            }
        }
    ]
}

hero.dart //如果不介意的话,用教程例子来说明如何输出数据

  class Hero {
  final int id;
  String name;

  Hero(this.id, this.name);

  factory Hero.fromJson(Map<String, dynamic> hero) =>
      Hero(_toInt(hero['id']), hero['name']);

  Map toJson() => {'id': id, 'name': name};
  }

  int _toInt(id) => id is int ? id : int.parse(id);

hero_service.dart

  import 'dart:async';
  import 'dart:convert';

  import 'package:http/http.dart';

  import 'hero.dart';

  class HeroService {
  static final _headers = {'Content-Type': 'application/json'};
  static const _heroesUrl = 'http://127.0.0.1:8000/heroes'; // источник получения данных
  final Client _http;

  HeroService(this._http);

  Future<List<Hero>> getAll() async {
    try {
      final response = await _http.get(_heroesUrl);
      final heroes = (_extractData(response) as List)
          .map((value) => Hero.fromJson(value))
          .toList();
      return heroes;
    } catch (e) {
      throw _handleError(e);
    }
  }

  Future<Hero> create(String name) async {
    try {
      final response = await _http.post(_heroesUrl,
          headers: _headers, body: json.encode({'name': name}));
      return Hero.fromJson(_extractData(response));
    } catch (e) {
      throw _handleError(e);
    }
  }

  dynamic _extractData(Response resp) => json.decode(resp.body)['data'];

  Exception _handleError(dynamic e) {
    print(e); // for demo purposes only
    return Exception('Server error; cause: $e');
   }
  }

我工作时没有出错,他只是无法理解角色......

您的 "name" 在 **attributes** 对象内部的样本 json 中下降了一个级别..所以它将是:

class Hero {
  final int id;
  String name;

  Hero(this.id, this.name);

  factory Hero.fromJson(Map<String, dynamic> hero) =>
      Hero(_toInt(hero['id']), hero['**attributes**']['name']);

  Map toJson() => {'id': id, 'name': name};
  }

  int _toInt(id) => id is int ? id : int.parse(id);

重要的是,JSON 的任何级别的复杂性都不能在解码后通过 Map and/or List 的 parent/child 关系在 Dart 中表示。