如何创建嵌套的json作为HttpPost实体

所以我创建了一个unit testing,将一些参数传递给特定的url。 所以这是我传递一些简单参数的方法:

HttpPost request = new HttpPost(server.getURL() + "/report/xxx"); String jsonData = "{\"reportId\":\"my_report\",\"name\":\"my_name\"}"; HttpEntity entJson = new StringEntity(jsonData, "application/json", "UTF-8"); request.setEntity(entJson); 

这工作正常,但我不知道怎么做,当我有这样的嵌套json:

 { "reportId" : "my_report", "name" : "my_name", "subReports" : [ { "id" : 144, "reportId" : "10", "name" : "my_name10", }, { "id" : 145, "reportId" : "11", "name" : "my_name11", } ] } 

这些是我试过的代码:

(1)

 HttpPost request = new HttpPost(server.getURL() + "/report/xxx"); JSONObject report = new JSONObject(); report.put("reportId", "my_report"); report.put("name", "my_name"); JSONObject subReport = new JSONObject(); subReport.put("id", "144"); subReport.put("reportId", "10"); subReport.put("name", "my_name10"); report.put("subReport", subReport); String jsonStr = report.toString(); request.setEntity(new StringEntity(jsonStr)); request.setHeader("Content-type", "application/json"); 

(2)

 HttpPost request = new HttpPost(server.getURL() + "/report/xxx"); String jsonData = "{\"reportId\":\"my_report\",\"name\":\"my_name\",\"subReport\":[{\"id\":144,\"reportId\":\"10\",\"name\":\"my_name10\",}]}"; HttpEntity entJson = new StringEntity(jsonData, "application/json", "UTF-8"); request.setEntity(entJson); 

这两个都没有工作。 还有其他方法吗?

对方法#1进行了一些更改,

 JSONObject report = new JSONObject(); report.put("reportId", "my_report"); report.put("name", "my_name"); //define json array to represent your sub report array JSONArray subReportArr = new JSONArray(); JSONObject subReport1 = new JSONObject(); subReport1.put("id", "144"); subReport1.put("reportId", "10"); subReport1.put("name", "my_name10"); //put subreport object to array subReportArr.put(subReport1); //for subReportn create JSONObject and populate with required data JSONObject subReportn = new JSONObject(); //then put into parent JSONArray subReportArr.put(subReportn); //put subReport array to main report object report.put("subReport", subReportArr); String jsonStr = report.toString(); //then print out System.out.println(jsonStr); 

输出:

{"name":"my_name","reportId":"my_report","subReport":[{"id":"144","name":"my_name10","reportId":"10"}]}

在json格式中,

  • {}代表JSONObject

  • []代表JSONArray