json_serializable 反序列化失败

json_serializable fails to deserialize

我正在尝试为我的 flutter 项目添加 json 支持,但很难做到正确。

我喜欢 flutter,但说到 json 我希望使用 gson。

我创建了一个小项目来说明我的问题。

请看https://bitbucket.org/oakstair/json_lab

我收到错误 type 'Match' is not a subtype of type 'Map' in type cast when trying to 运行 the simple 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);
}

因为我看不到您的 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
  };
}

我刚刚将这个问题的解决方案提交给了 repo。

我必须添加 explicitToJson。

@JsonSerializable(explicitToJson: true)