我需要在使用GSON(序列化/反序列化库)的同时为模型类实现Serializable吗 [英] Do i need to implement Serializable for model classes while using GSON(serialization/deserialization library)

查看:620
本文介绍了我需要在使用GSON(序列化/反序列化库)的同时为模型类实现Serializable吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用默认的HttpUrlConnection类进行api调用,并使用 GSON 将Java对象转换为json请求将json和json响应转换为等效的Java对象.我创建了各种模型(pojo类)以将请求/响应转换为模型对象.由于GSON是序列化/反序列化库,我怀疑对所有这些模型实现Serializable是理想的吗? /p>

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?

推荐答案

取决于您要对它们执行什么操作,但很可能不需要这样做.可序列化是在Java中序列化数据的一种方法,类似于默认的Java方法. JSON序列化是另一个. Parcelable是Android专用的三分之一.唯一需要使用Serializable的是将其传递给采用Serializable作为参数的API.如果您不需要这样做,那么使用GSON进行序列化而不执行Serializable就可以了.

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.

这篇关于我需要在使用GSON(序列化/反序列化库)的同时为模型类实现Serializable吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆