Android: convert Parcelable to JSON

∥☆過路亽.° 提交于 2020-01-05 03:39:06

问题


I am working with socket.io library which emits messages to the socket.io server. The server expects JSON objects, arrays, etc. My original implementation used JSONOject and JSONArray datatypes. However, I would like to switch to using classes generated via Parceler library. The classes generated with library's annotations can be wrapped into Parcels. It seems like a very convenient way of managing such communication. However, is there a way to convert Parceler's class or a Parcel class into a JSON string or JSONObject/Array?

GSON library supports toJson method and I know that Retrofit does some magic with Parcels, JSON, and GSON.


回答1:


i guess this will help you,

Create a class with getters and setters method for example

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

than you can create json from the object of this class:

new Gson().toJson(a)

Or object from json:

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


来源:https://stackoverflow.com/questions/28495830/android-convert-parcelable-to-json

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