Rustam Ibragimov
Rustam Ibragimov

Reputation: 2707

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.

Upvotes: 3

Views: 6140

Answers (2)

Mohmad Iqbal Lone
Mohmad Iqbal Lone

Reputation: 459

I would go with this approach.

1- Create a Pojo class which implements serializable

2- Build the object of that class

3- Send the Object as serialazable one

public class POJO implements Serializable{
    private String sessionId;
    private String status;
   // private JSONObject typeAttributes;
    // SUPPOSE THIS JSONObject CONTAINS TWO FIELDS AS NAME AND AGE SO I USE TWO MORE FILDS
    String name;
    String age;

    //....... WRITE GETTERS AND SETTERS

}

Let me know if you need further explanation for building this POJO object Inside activity and then send it to as a serializable

Upvotes: 1

roarster
roarster

Reputation: 4086

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.

Upvotes: 11

Related Questions