2011-09-08 12 views
21

シリアル化でJSONを使用するAndroidの簡単な例はありますか?AndroidのJSON - シリアル化

おかげ

+1

あなたはこのhttp://blog.brianbuikema.com/2010/04/android-how-to-deserialize-both-xml-and-json/ –

+0

それがある可能性があり意味しました、ありがとう – Waypoint

答えて

39

我々はそのためgsonライブラリを使用しています。シリアル化はあなただけでJSONをシリアライズ(デ)にあなたのAndroidプロジェクト内の別のライブラリを使用しないようにしたい場合は、コードとして、以下の使用をCAU

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

new Gson().toJson(obj) 

とデシリアライズのために呼び出すのと同じくらい簡単です私がやります。

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

をシリアル化すると、(デ)への単純なライブラリがあり

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

よろしく、マーティン

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

をデシリアライズするには、Android独自のJSONとの互換性がJSONを、シリアライズ

としょうかん。

// 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