2013-07-23 20 views
84

Come posso creare un JSON con questo formato in Android: Poiché l'API che passerò analizzerà JsonArray quindi l'oggetto. O sarebbe giusto se solo per passare un oggetto JSON? Dal momento che dovrò solo inserire 1 transazione per chiamata di servizio.Android- crea JSON Array e JSON Object

{ 
    "student": [ 
     { 
      "id": 1, 
      "name": "John Doe", 
      "year": "1st", 
      "curriculum": "Arts", 
      "birthday": 3/3/1995 
     }, 
     { 
      "id": 2, 
      "name": "Michael West", 
      "year": "2nd", 
      "curriculum": "Economic", 
      "birthday": 4/4/1994 
     } 
    ] 
} 

Quello che so è solo il JSONObject. Come questo.

JSONObject obj = new JSONObject(); 
try { 
    obj.put("id", "3"); 
    obj.put("name", "NAME OF STUDENT"); 
    obj.put("year", "3rd"); 
    obj.put("curriculum", "Arts"); 
    obj.put("birthday", "5/5/1993"); 
} catch (JSONException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} 

Qualsiasi idea. Grazie

+1

qual è l'isseu? – Blackbelt

+1

[link di riferimento] (http://chintankhetiya.wordpress.com/2013/05/27/83/) –

+0

inserendo JSONObject in un JSONArray per ottenere il formato pubblicato. – sftdev

risposta

214

utilizzare il seguente codice:

JSONObject student1 = new JSONObject(); 
try { 
    student1.put("id", "3"); 
    student1.put("name", "NAME OF STUDENT"); 
    student1.put("year", "3rd"); 
    student1.put("curriculum", "Arts"); 
    student1.put("birthday", "5/5/1993"); 

} catch (JSONException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} 

JSONObject student2 = new JSONObject(); 
try { 
    student2.put("id", "2"); 
    student2.put("name", "NAME OF STUDENT2"); 
    student2.put("year", "4rd"); 
    student2.put("curriculum", "scicence"); 
    student2.put("birthday", "5/5/1993"); 

} catch (JSONException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} 


JSONArray jsonArray = new JSONArray(); 

jsonArray.put(student1); 
jsonArray.put(student2); 

JSONObject studentsObj = new JSONObject(); 
    studentsObj.put("Students", jsonArray); 



String jsonStr = studentsObj.toString(); 

    System.out.println("jsonString: "+jsonStr); 
+0

Perfetto esempio! –

4
JSONObject obj = new JSONObject(); 
      try { 
       obj.put("id", "3"); 
       obj.put("name", "NAME OF STUDENT"); 
       obj.put("year", "3rd"); 
       obj.put("curriculum", "Arts"); 
       obj.put("birthday", "5/5/1993"); 

      } catch (JSONException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
      JSONArray js=new JSONArray(obj.toString()); 
      JSONObject obj2 = new JSONObject(); 
      obj2.put("student", js.toString()); 
+0

presumo che 'obj' in 'JSONObject obj2 = new JSONObject(); obj.put ("studente", js.toString()); ' è 'obj2'? – sftdev

4

È possibile creare un un metodo e passare paramters ad esso e ottenere il JSON come risposta.

private JSONObject jsonResult(String Name,int id, String curriculum) throws JSONException { 
     JSONObject json = null; 
     json = new JSONObject("{\"" + "Name" + "\":" + "\"" + Name+ "\"" 
      + "," + "\"" + "Id" + "\":" + id + "," + "\"" + "Curriculum" 
      + "\":" + "\"" + curriculum+ "\"" + "}"); 
     return json; 
     } 

Spero che questo ti possa aiutare.

21
public JSONObject makJsonObject(int id[], String name[], String year[], 
      String curriculum[], String birthday[], int numberof_students) 
      throws JSONException { 
     JSONObject obj = null; 
     JSONArray jsonArray = new JSONArray(); 
     for (int i = 0; i < numberof_students; i++) { 
      obj = new JSONObject(); 
      try { 
       obj.put("id", id[i]); 
       obj.put("name", name[i]); 
       obj.put("year", year[i]); 
       obj.put("curriculum", curriculum[i]); 
       obj.put("birthday", birthday[i]); 

      } catch (JSONException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
      jsonArray.put(obj); 
     } 

     JSONObject finalobject = new JSONObject(); 
     finalobject.put("student", jsonArray); 
     return finalobject; 
    } 
+0

Grazie per questo semplice metodo. – KishuDroid

2

hanno lottato con questo finché non ho trovato la risposta: biblioteca

  1. Uso GSON:

    Gson gson = Gson(); 
    String str_json = gson.tojson(jsonArray);` 
    
  2. passare la matrice JSON. Questo sarà auto-stringa. Questa opzione ha funzionato perfettamente per me.

0
JSONObject jsonResult = new JSONObject(); 
try { 
    jsonResult.put("clave", "valor"); 
    jsonResult.put("username", "iesous"); 
    jsonResult.put("password", "1234"); 

} catch (JSONException e) { 
    // TODO Auto-generated catch block 
e.printStackTrace(); 
} 

Log.d("DEV","jsonResult->"+jsonResult); 
+2

È necessario aggiungere alcuni elementi narrativi per spiegare la risposta e migliorare la formattazione. – rghome

1

Ecco una versione più semplice (ma non così breve) che non richiede try-catch:

Map<String, String> data = new HashMap<>(); 
data.put("user", "[email protected]"); 
data.put("pass", "123"); 

JSONObject jsonData = new JSONObject(data); 

Se si desidera aggiungere un JsonObject in un campo, si può fare in questo modo:

data.put("socialMedia", (new JSONObject()).put("facebookId", "1174989895893400")); 
data.put("socialMedia", (new JSONObject()).put("googleId", "106585039098745627377")); 

Sfortunatamente ha bisogno di un try-catch a causa del metodo put().

SE si vuole evitare di nuovo try-catch (non molto raccomandato, ma è ok se si può garantire le stringhe JSON ben formattati), si potrebbe fare in questo modo:

data.put("socialMedia", "{ 'facebookId': '1174989895893400' }"); 

Si può fare lo lo stesso per JsonArrays e così via.

Cheers.