我正在尝试为我的flutter项目添加json支持,但是要正确设置它有些困难。
我喜欢扑打,但是当涉及到json时,我希望gson。
我创建了一个小项目来说明我的问题。
请https://bitbucket.org/oakstair/json_lab
我得到了错误 尝试运行往返于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);
}
答案 0 :(得分:0)
Because I cannot see your json data I've made assumptions on the information you've provided on naming the objects. You'll need to change the following to match the json names (case sensitive).
Try the following to create your Match object
@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
};
}
答案 1 :(得分:0)
我刚刚针对此问题向存储库提交了解决方案。
我必须添加explicitToJson。
@JsonSerializable(explicitToJson: true)