如何解析大写json之间的json数据以在Flutter中进行分类

时间:2019-09-24 09:32:40

标签: flutter dart

从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":[]}

1 个答案:

答案 0 :(得分:0)

  1. 从PHP服务返回的JSON错误。 SESSIONID是一个字符串,因此必须用“双引号”引起来
  2. Dart 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],
....
});