Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep fields sequence in Gson serialization

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"));

The string jsonRequest can be:

  • { "bar":"bar", "baz":"baz" } (correct)
  • { "baz":"baz", "bar":"bar" } (wrong sequence)
like image 542
Sergey Romanovsky Avatar asked Jun 16 '11 00:06

Sergey Romanovsky


People also ask

Does Gson serialize static fields?

gson. GsonBuilder works this way for the same reason. Static fields are not serializable because static fields are class variables , they are not specific for particular instance of that class.

Does Gson ignore extra fields?

3. Deserialize JSON With Extra Unknown Fields to Object. As you can see, Gson will ignore the unknown fields and simply match the fields that it's able to.

How do you serialize with Gson?

Serialization in the context of Gson means converting a Java object to its JSON representation. In order to do the serialization, we need to create the Gson object, which handles the conversion. Next, we need to call the function toJson() and pass the User object. Program output.

Does Gson ignore transient fields?

Gson serializer will ignore every field declared as transient: String jsonString = new Gson().


2 Answers

You'd need to create a custom JSON serializer.

E.g.

public class FooJsonSerializer implements JsonSerializer<Foo> {      @Override     public JsonElement serialize(Foo foo, Type type, JsonSerializationContext context) {         JsonObject object = new JsonObject();         object.add("bar", context.serialize(foo.getBar());         object.add("baz", context.serialize(foo.getBaz());         // ...         return object;     }  } 

and use it as follows:

Gson gson = new GsonBuilder().registerTypeAdapter(Foo.class, new FooJsonSerializer()).create(); String json = gson.toJson(foo); // ... 

This maintains the order as you've specified in the serializer.

See also:

  • Gson User Guide - Custom serializers and deserializers
like image 110
BalusC Avatar answered Sep 22 '22 02:09

BalusC


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.

like image 23
StaxMan Avatar answered Sep 23 '22 02:09

StaxMan