2011-09-08 27 views
21

Esiste un semplice esempio per Android di utilizzo di JSON in una serializzazione?JSON su Android - serializzazione

Grazie

+1

Forse voi significa questo http://blog.brianbuikema.com/2010/04/android-how-to-deserialize-both-xml-and-json/ –

+0

Potrebbe essere che , Grazie – Waypoint

risposta

39

Usiamo la libreria gson per questo. La serializzazione è semplice come chiamare

new Gson().toJson(obj) 

E per la deserializzazione,

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

Se si vuole evitare di utilizzare un'altra libreria nel progetto Android solo per (de) serializzare JSON, è CAU uso seguente codice come Lo voglio.

Per serializzare

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

e per deserializzare

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

saluti, Martin

-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

v'è una semplice libreria per (de) serializzare JSON, compatibile con proprio JSON Android biblioteca.

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

Problemi correlati