34

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

Thanks

0

4 Answers 4

63

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);
Sign up to request clarification or add additional context in comments.

1 Comment

deserialization : MyClass myClass = new Gson().fromJson(jsonStr, MyClass.class);
27

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();
}

2 Comments

This is cool, but I can't imagine it working well for larger sets of complicated JSON
You're absolutely right, this is suitable for quite simple and reasonably small JSONs. :-)
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

Comments

-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();
            }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.