33

is there any simple example for Android of using JSON in a serialization?

Thanks

Waypoint
  • 17,283
  • 39
  • 116
  • 170

4 Answers4

62

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);
Asapha
  • 643
  • 8
  • 14
alex.zherdev
  • 23,914
  • 8
  • 62
  • 56
29

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();
}
Alexander Farber
  • 21,519
  • 75
  • 241
  • 416
Martin Edlman
  • 665
  • 7
  • 15
0

There is a simple library to (de)serialize JSON,compatible with android own json library.

// deserialize a java bean to json object 
JSONObject studentJson = JsonDeer.toJson(student);
// serialize a java bean from json object
Student student1 = JsonDeer.fromJson(studentJson,Student.class);

library address

Rico Teng
  • 236
  • 1
  • 7
-1
    protected void onPostExecute(String results) {
        if (results!=null) {
            try {
                Tec tec_m=new Tec();

                tec_m=new Gson().fromJson(results, Technician.class);

                ((AndroidActivity)activity).setData(tec_m);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
gilix
  • 545
  • 10
  • 14