JSON on Android - serialization

We use the gson library for that. Serialization is as simple as calling

new Gson().toJson(obj)

And for deserialization,

new Gson().fromJson(jsonStr, MyClass.class);

If you want to avoid using another library in your Android project just to (de)serialize JSON, you cau use following code as I do.

To serialize

JSONObject json = new JSONObject();
json.put("key", "value");
// ...
// "serialize"
Bundle bundle = new Bundle();
bundle.putString("json", json.toString());

and to deserialize

Bundle bundle = getBundleFromIntentOrWhaterver();
JSONObject json = null;
try {
    json = new JSONObject(bundle.getString("json"));
    String key = json.getString("key");
} catch (JSONException e) {
    e.printStackTrace();
}

Tags:

Json

Android