Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
456 views
in Technique[技术] by (71.8m points)

android - Passing JSONObject to another activity via Intent

I know what to do with the method jsonObj.toString() but I have a reason to can not do so. My JSONObject has a JSONArray inside that has too much data, so If I convert it to String then transform back that I afraid of it reaches the limit of String type. So I want to pass a pure object rather than use that method. I implement Parcelable interface to do that but I got the error "java.lang.RuntimeException: Parcel: unable to marshal value"

public class MJSONObject implements Parcelable {
private JSONObject jsonObject;

public MJSONObject() {
}

public MJSONObject(JSONObject jsonObject) {
    this.jsonObject = jsonObject;
}

public void set(JSONObject jsonObject) {
    this.jsonObject = jsonObject;
}

public JSONObject get() {
    return jsonObject;
}

@Override
public int describeContents() {
    // TODO Auto-generated method stub
    return 0;
}

public static final Parcelable.Creator<MJSONObject> CREATOR = new Parcelable.Creator<MJSONObject>() {
    public MJSONObject createFromParcel(Parcel in) {
        return new MJSONObject(in);
    }

    public MJSONObject[] newArray(int size) {
        return new MJSONObject[size];
    }
};

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeValue(jsonObject);
}

private MJSONObject(Parcel in) {
    jsonObject = (JSONObject) in.readValue(JSONObject.class.getClassLoader());
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can easily pass your JSONObject by converting it in String like in some scenarios we send JSONObject with url by appending it as a String. So, Try to send it as String like:

intent.putExtra("jsonObject", jsonObject.toString());

And receive it on other side

Intent intent = getIntent();

String jsonString = intent.getStringExtra("jsonObject");

Now you have your JSON in a String named jsonString assume it as a response like when you received from Web Service and then get your JSONObject like:

JSONObject jObj = new JSONObject(jsonString);

hope you will understand what my point is :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...