问题
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