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)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.
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.
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.
Gson serializer will ignore every field declared as transient: String jsonString = new Gson().
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With