如何在Android中以这种格式创建JSON:由于我将传递的API将解析JsonArray,然后解析该对象。还是只传递一个json对象就可以了吗?因为我只需要在每个服务调用中插入1个事务即可。
{ "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 } ] }
我所知道的只是JSONObject。像这个。
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(); }
有任何想法吗。谢谢
使用以下代码:
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);