javajsongsonserializable

Should a Class which is serialzied with GSON to JSON implement the Serializable Interface


I have this POJO which is being serialzied to JSON using new Gson().toJson(entity) Should I implement the Serializable Interface on this POJO?

@Data
public class BankcodeJSONEntity {

    @NotNull
    @Size(min = 8, max = 8)
    private String bankcode;
    @NotNull
    @Size(min = 11, max = 11)
    private String bic;
    @NotNull
    private String ticket;

    @Basic
    @Temporal(TemporalType.DATE)
    @NotNull
    private Date date;
    @NotNull
    private String category;
    @NotNull
    private String name;

}

Solution

  • No, it is not necessary. Gson use reflection in order to produce the desired json. You should implements Serializable when:

    1. save it on disk
    2. send it through a socket as an Object

    For example, if you have a web application deployed in HA on two or more nodes in cluster (then they exchange the session each other), and you use a session scope to save user authentication, the bean that contains this information must be serializable.

    If you decide to use Serializable add a serialVersionUID. This is a long used by the JVM to identify in an unique manner the object itself.

    When you don't sepcify it, the compiler add a generated one (that is therefore compiler dependent) and this identity changes when you change your object, for example adding a field; this means that after a minimal change, you shouldn't deserialize objects serialized before the change.