31

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

Thanks

Waypoint
  • 16,445
  • 37
  • 114
  • 168

4 Answers4

57

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
  • 506
  • 6
  • 12
alex.zherdev
  • 23,490
  • 8
  • 60
  • 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
  • 19,827
  • 73
  • 224
  • 393
Martin Edlman
  • 635
  • 6
  • 12
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
  • 547
  • 10
  • 14