Android: convert Parcelable to JSON

Vadym picture Vadym · Feb 13, 2015 · Viewed 7.6k times · Source

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.

Answer

dvs picture dvs · Feb 13, 2015

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