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

问题描述 投票:0回答:1

在angulardart教程中,您无法找到比示例更复杂的JSON信息link to the tutorial

brauser django rest框架中的json

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');
   }
  }

我在工作时没有错误,他只是无法直达角色...image

json django-rest-framework angular-dart json-api
1个回答
0
投票
您的“名称”位于**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);

重要的是,解码后,无法通过Map和/或List的父/子关系在Dart中表示JSON的任何复杂程度。 
© www.soinside.com 2019 - 2024. All rights reserved.