Answer the question
In order to leave comments, you need to log in
Google GSON: how to change serialization order of fields when inheriting?
Good afternoon, Habrausers!
There is a POJO inheritance structure like this:
public class Reply{
private int code;
}
public class ConcreteReply extends Reply{
private String concreteStr;
}
{ "concreteStr":"value", "code":0 }
{ "code":0, "concreteStr":"value" }
Answer the question
In order to leave comments, you need to log in
1. If your application depends on serialization order, then you are making a mistake.
2. In Java reflection, the order of fields is not guaranteed. This means that any tools that use it also do not guarantee it without additional gestures.
3. If you still need this crutch, you will have to write your own serializer.
4. If GSON is not critical, then you can use Jackson instead. There, the serialization order can be specified using annotations.
Actually it is not critical.
For example, there are such objects:
public class Error{
private int code;
}
public class ErrorWithTrace extends Error{
private String trace;
}
it will be much better if in case of ErrorWithTrace such JSON will come:
{"code":111, "trace":"here very very long stack trace for Java" }
than this one:
{"trace":"here very very long stack trace for Java","code":111}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question