Do i need to implement Serializable for model classes while using GSON(serialization/deserialization library)

为君一笑 提交于 2020-01-03 16:50:49

问题


I have used default HttpUrlConnection class to make api calls and GSON to convert Java Objects into json request and json response into equivalent Java object.I have created various models(pojo class) to convert the request/response to model objects.My doubt is that is it ideal to implement Serializable to all those models since GSON is serialization/deserialization library?

public class Contact implements Serializable {
    private String name;
    private String email;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

I removed implements Serializable from all models and everything seems to be wroking fine.But i am confused is it correct or not?


回答1:


Depends on what you want to do with them, but most likely you don't need to. Serializable is one way to serialize data within Java that's sort of the default Java way. JSON serialization is another. Parcelable is a third that's Android specific. The only time you need to use Serializable is if you want to pass it to an API that takes a Serializable as a parameter. If you don't need to do that then using GSON to serialize and not implementing Serializable is just fine.

The difference between those 3 methods is the format of the data they output to. The different formats have different pros and cons, but they'l all get the job done.



来源:https://stackoverflow.com/questions/41429799/do-i-need-to-implement-serializable-for-model-classes-while-using-gsonserializa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!