Android: convert Parcelable to JSON

2019-07-21 14:40发布

问题:

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);