【问题标题】:Android: convert Parcelable to JSONAndroid:将 Parcelable 转换为 JSON
【发布时间】:2015-02-13 09:01:42
【问题描述】:

我正在使用向 socket.io 服务器发送消息的 socket.io 库。服务器需要 JSON 对象、数组等。我最初的实现使用 JSONOject 和 JSONArray 数据类型。但是,我想改用通过Parceler 库生成的类。使用库的注释生成的类可以包装到 Parcels 中。这似乎是管理此类通信的一种非常方便的方式。但是,有没有办法将 Parceler 的类或 Parcel 类转换为 JSON 字符串或 JSONObject/Array?

GSON 库支持 toJson 方法,而且我知道 Retrofit 对 Parcels、JSON 和 GSON 有一些魔力。

【问题讨论】:

    标签: android json gson parcelable parceler


    【解决方案1】:

    我想这会对你有所帮助,

    例如用getter和setter方法创建一个类

    class A
    {
    int b;
    void setb(int x){this.b = x;}
    int getb(){return this.b}
    }
    

    你可以从这个类的对象创建 json:

    new Gson().toJson(a)
    

    或来自 json 的对象:

    a = new Gson().fromJson(data, A.class);
    

    【讨论】:

    • 是的,这对我有用。我阅读了文档,但之前没有尝试过。
    猜你喜欢
    • 2021-12-04
    • 1970-01-01
    • 2015-05-30
    • 1970-01-01
    • 2013-04-25
    • 1970-01-01
    • 2021-03-20
    • 1970-01-01
    相关资源
    最近更新 更多