【问题标题】:json_serializable fails to deserializejson_serializable 无法反序列化
【发布时间】:2019-02-26 11:15:21
【问题描述】:

我正在尝试将 json 支持添加到我的颤振项目中,但很难做到正确。

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

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

请关注https://bitbucket.org/oakstair/json_lab

我得到了错误 在尝试运行简单的 to/from json 测试时,类型 'Match' 不是类型转换中类型 'Map' 的子类型

这里显然有一些我想念的东西!

提前感谢暴风雨的斯德哥尔摩!

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 flutter json-deserialization jsonserializer


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    我必须添加explicitToJson。

    @JsonSerializable(explicitToJson: true)
    

    【讨论】:

      猜你喜欢
      • 2019-09-18
      • 1970-01-01
      • 2018-03-06
      • 1970-01-01
      • 2016-12-30
      • 1970-01-01
      • 2021-11-08
      • 1970-01-01
      • 2018-12-02
      相关资源
      最近更新 更多