如何在Gson序列化中保持字段序列 [英] How to keep fields sequence in Gson serialization

查看:1135
本文介绍了如何在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}(这是错误的顺序)



<如果GSON不支持字段顺序的定义,那么还有其他的库可以这样做。

例如, Jackson 允许用@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序列化中保持字段序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆