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

时间:2014-09-23 09:11:30

标签: java json spring

所以我创建了一个单元测试,将一些参数传递给特定的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 个答案:

答案 0 :(得分:2)

您的方法#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