开发者社区> 问答> 正文

Android-创建JSON数组和JSON对象

如何在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

展开
收起
保持可爱mmm 2020-02-07 23:09:32 468 0
1 条回答
写回答
取消 提交回答
  • 使用以下代码:

    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);
    
    2020-02-07 23:09:46
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
58同城Android客户端Walle框架演进与实践之路 立即下载
Android组件化实现 立即下载
蚂蚁聚宝Android秒级编译——Freeline 立即下载