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

查看:39
本文介绍了如何在 Gson 序列化中保持字段顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎 Gson.toJson(Object object) 生成带有随机分布的对象字段的 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 可以是:

The string jsonRequest can be:

  • { "bar":"bar", "baz":"baz";}(正确)
  • { "baz":"baz", "bar":"bar";}(顺序错误)
  • { "bar":"bar", "baz":"baz" } (correct)
  • { "baz":"baz", "bar":"bar" } (wrong sequence)

推荐答案

如果 GSON 不支持字段顺序的定义,那么还有其他库支持.例如,Jackson 允许使用 @JsonPropertyOrder 定义它.必须指定自己的自定义序列化程序对我来说似乎是一项艰巨的工作.

是的,我同意根据 JSON 规范,应用程序不应期望字段的特定顺序.

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天全站免登陆