如何在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(); } 有任何想法吗。谢谢 问题来源于stack overflow
使用以下代码:
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);
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。