How to keep fields sequence in Gson serialization

Viewed 34014

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)
4 Answers

Actually Gson.toJson(Object object) doesn't generate fields in random order. The order of resulted json depends on literal sequence of the fields' names.

I had the same problem and it was solved by literal order of properties' names in the class.

The example in the question will always return the following jsonRequest:

{ "bar":"bar", "baz":"baz" }

In order to have a specific order you should modify fields' names, ex: if you want baz to be first in order then comes bar:

public class Foo {
    public String f1_baz;
    public String f2_bar;

    public Foo ( String f1_baz, String f2_bar ) {
        this.f1_baz = f1_baz;
        this.f2_bar = f2_bar;
    }
}

jsonRequest will be { "f1_baz ":"baz", "f2_bar":"bar" }

Related