Search code examples
androidserializationparcelable

Android Parcelable with JsonObject


In order to initialize my new Fragment, I need to send an object as parcelable one. These are the fields it contains:

private String sessionId;
private String status;
private JSONObject typeAttributes;
private JSONObject kindAttributes;

The problem is that JSONObject is not parcelable. If I just use writeValue method in writeToParcel method, I get unacceptable class error. Moreover, JSONObject is not even Serializable.

Also, typeAttributes and kindAttributes are dynamic, so each time my app starts they have different fields with different values.

If anyone knows how to solve it, please help.


Solution

  • I would use JSONObject's toString() method to return a String which you can easily save to a parcel.

    Then to create the object from the parceled String, just use the JSONObject constructor that takes a String and it'll auto-populate those object's fields for you.