本文介绍了如何在Gson序列化中保持字段序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
看起来像Gson.toJson(对象对象)生成JSON代码与对象的随机传播领域。
public class Foo {
public String bar;
public String baz;
public Foo(String bar,String baz){
this.bar = bar;
this.baz = baz;
}
}
Gson gson = new Gson();
String jsonRequest = gson.toJson(new Foo(bar,baz));
// jsonRequest现在可以是{bar:bar,baz:baz}(这是正确的)
//可以是{baz: baz,bar:bar}(这是错误的顺序)
例如,允许用@JsonPropertyOrder来定义它。不得不指定自己的自定义序列化器对我来说看起来很糟糕。
是的,我同意按照JSON规范,应用程序不应该期望字段的具体排序。
Seems like Gson.toJson(Object object) generates JSON code with randomly spread fields of the object. Is there way to fix fields order somehow?
public class Foo {
public String bar;
public String baz;
public Foo( String bar, String baz ) {
this.bar = bar;
this.baz = baz;
}
}
Gson gson = new Gson();
String jsonRequest = gson.toJson(new Foo("bar","baz"));
// jsonRequest now can be { "bar":"bar", "baz":"baz" } (which is correct)
// and can be { "baz":"baz", "bar":"bar" } (which is a wrong sequence)
Thanks.
解决方案
If GSON doesn't support definition of field order, there are other libraries that do. Jackson allows definining this with @JsonPropertyOrder, for example. Having to specify one's own custom serializer seems like awful lot of work to me.
And yes, I agree in that as per JSON specification, application should not expect specific ordering of fields.
这篇关于如何在Gson序列化中保持字段序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!