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

Issue

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

json in brauser django rest framework

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
//if you don’t mind, use the tutorial example to show how to output data

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

I don’t get errors when working, he just can’t get through to the characters…
image

Solution

Your “name” is down a level in the sample json inside of the **attributes** object .. so it would be:

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

It’s important to not that any level of complexity of JSON can be represented in Dart through parent/child relationships of Map and/or List after being decoded.

Answered By – Brian Gorman

Answer Checked By – Pedro (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *