开发者

JSON on Android - serialization

开发者 https://www.devze.com 2023-04-03 06:51 出处:网络
is the开发者_StackOverflow社区re any simple example for Android of using JSON in a serialization?

is the开发者_StackOverflow社区re any simple example for Android of using JSON in a serialization?

Thanks


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


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


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

精彩评论

暂无评论...
验证码 换一张
取 消