json_serializable не может десериализовать - PullRequest
0 голосов
/ 22 сентября 2018

Я пытаюсь добавить поддержку json в свой проект флаттера, но мне трудно это понять.

Я люблю флаттер, но когда дело доходит до json, я желаю gson.

IЯ создал небольшой проект, который иллюстрирует мою проблему.

Пожалуйста, наберите https://bitbucket.org/oakstair/json_lab

Я получаю сообщение об ошибке тип 'Match' не является подтипом типа 'Map' в приведении типа при попытке запустить простой to / from тест json.

Очевидно, что здесь я что-то упускаю!

Заранее спасибо из бурного Стокгольма!

import 'package:json_annotation/json_annotation.dart';

part 'json_lab.g.dart';

@JsonSerializable()
class Match {
  int home;
  int away;
  double homePoints;
  double awayPoints;

  Match(this.home, this.away, {this.homePoints, this.awayPoints});

  factory Match.fromJson(Map<String, dynamic> json) => _$MatchFromJson(json);
  Map<String, dynamic> toJson() => _$MatchToJson(this);
}

@JsonSerializable()
class Tournament {

  List<String> participants; // Teams or Players.
  List<List<Match>> table = new List<List<Match>>();

  Tournament(this.participants, {this.table});

  factory Tournament.fromJson(Map<String, dynamic> json) => _$TournamentFromJson(json);
  Map<String, dynamic> toJson() => _$TournamentToJson(this);
}

1 Ответ

0 голосов
/ 23 сентября 2018

Поскольку я не могу видеть ваши данные json, я сделал предположения относительно информации, которую вы предоставили для именования объектов.Вам нужно изменить следующее, чтобы соответствовать именам json (с учетом регистра).

Попробуйте создать следующее для вашего объекта Match

@JsonSerializable(nullable: true) //allow null values
class Match extends Object with _$MatchSerializerMaxin {
  int home;
  int away;
  double homePoints;
  double awayPoints;

  Match({this.home, this.away, this.homePoints, this.awayPoints});

  factory Match.fromJson(Map<String, dynamic> json) => _$MatchFromJson(json);

  Map<String, dynamic> toMap() {
    var map = new Map<String, dynamic>();

    map["Home"] = home;
    map["Away"] = away;
    map["HomePoints"] = homePoints;
    map["AwayPoints"] = awayPoints;

    return map;
  }

  Match.fromMap(Map map){
    try{
      home = map["Home"] as int;
      away =  map["Away"] as int;
      homePoints = map["HomePoints"] as double;
      awayPoints = map["AwayPoints"] as double;

    }catch(e){
      print("Error Match.fromMap: $e");
    }
  }
}

Match _$MatchFromJson(Map<String, dynamic> json){
  Match match = new Match(
    home: json['Home'] as int,
    away: json['Away'] as int,
    homePoints: json['HomePoints'] as double,
    awayPoints: json['AwayPoints'] as double,
  );

    return match;
}

abstract class _$MatchSerializerMaxin {
  int get home;
  int get away;
  double get homePoints;
  double get awayPoints;

  Match<String, dynamic> toJson() => <String, dynamic>{
    'Home' : home,
    'Away' : away,
    'HomePoints' : homePoints,
    'AwayPoints' : awayPoints
  };
}
...