从PHP服务器,我收到一个json数据 并在Flutter中使用类,我想将数据传输到类中。 但是由于大写或连字符,我无法将json数据解析为类类型。 也许那是php json数据和类之间的不一致问题。 但是我不能在Flutter类中使用大写字母或连字符。 该如何解决?
从PHP接收的数据 `{reset:true,SESSIONID:230hnoco0lnao6da7gqd9t5i56,chat_nations:.....}
** Flutter中定义的类**
class Post {
String id, sessionid;
bool error, reset;
List<ChatNation> chatNations = [];
Post({
this.reset,
this.sessionid,
List<ChatNation> chatNations,
this.error,
this.id,
});
factory Post.fromJson(Map<String, dynamic> json) => _$PostFromJson(json);
Map<String, dynamic> toJson() => _$PostToJson(this);
}
定义类的结果
{"id":null,"sessionid":null,"error":false,"reset":true,"chatNations":[]}
答案 0 :(得分:0)
json_annotation
具有JsonKey
注释,该注释可以采用JSON密钥的可选名称。因此,您可以将类Post
重写为@JsonSerializable()
class Post {
@JsonKey(nullable: true)
String id;
@JsonKey(nullable: false, name="SESSIONID")
String sessionid;
....
}
检查JsonKey
批注的文档。
但是,这种方法有一个问题:DART生成的JSON也将具有这些无关紧要的名称/键。
如果您要解决此问题,最好将自己的fromJson
实现方式编写为例如
Post fromJson(Map json) => Post({
sessionid: (json['sessionid'] ?? json['SESSIONID']) as String,
id: json[id],
....
});