假设有一个模型类
class Movie {
String id;
String title;
int year;
Production production;
public String getId() {
return id;
}
public String getTitle() {
return title;
}
public int getYear() {
return year;
}
public Production getProduction() {
return production;
}
};
使用gson会产生一个像这样的 json 字符串
movies: [
{
id: "771305050",
title: "Straight Outta Compton",
production: {
director: "F. Gary Gray"
screenplay: "Jonathan Herman"
},
year: 2015,
},
{
id: "771357161",
title: "Mission: Impossible Rogue Nation",
production: {
director: "Christopher McQuarrie",
screenplay: "Christopher McQuarrie"
},
year: 2015
}
]
如您所见,模型类中字段的顺序不同:production在 json 字符串中,现在它早于year. 是否有可能在不放弃库的情况下以模型类中的方式进行排序?
根据JSON 规范,一个对象是:
因此,应用程序不应依赖于关于字段顺序的假设。
现在更重要的是:
Gson 没有办法控制字段的顺序(至少我没听说过)。但是比如Jackson就有这样的手段,尤其是注解
@JsonPropertyOrder也就是说,如果您真的需要编写自己的反序列化器(Gson 允许您这样做)或使用 Jackson