C
C
cyberorg2013-10-28 09:17:12
Google
cyberorg, 2013-10-28 09:17:12

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;
}

By default, it is serialized into the following JSON: That is, first the child fields, then the parent fields. How to change this order so that the parent fields come first, and the child fields are already added at the end? In this example, the result of the method execution should be as follows:
{ "concreteStr":"value", "code":0 }
{ "code":0, "concreteStr":"value" }

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
Ruslan Lopatin, 2013-10-28
@lorus

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.

M
Mort, 2013-11-13
@Mort

Can you explain the criticality of the order of serialized fields?

K
kyberorg, 2013-11-13
@kyberorg

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 question

Ask a Question

731 491 924 answers to any question