Reputation: 491
So I was creating a unit test that passes some parameters to a specific url. So here's how I pass some simple parameters:
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);
This is working fine but I don't know how to do it when I have a nested json like this:
{
"reportId" : "my_report",
"name" : "my_name",
"subReports" : [
{
"id" : 144,
"reportId" : "10",
"name" : "my_name10",
}, {
"id" : 145,
"reportId" : "11",
"name" : "my_name11",
}
]
}
These are the codes that I tried:
(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);
None of the two are working. Are there other ways to do this?
Upvotes: 3
Views: 4720
Reputation: 3475
Some changes on your method #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"}]}
In json format,
{}
represents JSONObject
[]
represents JSONArray
Upvotes: 2