7

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?

Community
  • 1
  • 1
Android Developer
  • 9,157
  • 18
  • 82
  • 139

1 Answers1

7

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.

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
  • My api doesn't takes Serializable as a parameter..is there any cons if i implements Serializable when there is no need to serialize data?I have read that there is no disadvantage of implementing Serializable in terms of memory allocation and accessibility.. http://stackoverflow.com/questions/16789076/what-are-the-disadvantages-of-making-a-class-serializable-in-java – Android Developer Jan 02 '17 at 16:10
  • No cons except slightly more complicated code than needed. And really not by much. I wouldn't make removing it a priority if you already have it. In fact there are cases when you may want it anyway (I've sometimes had to deserialize an object from JSON then pass it to another Activity via Intent, which required Serializable). – Gabe Sechan Jan 02 '17 at 16:12