首页 > 解决方案 > 如 Postman 所示创建 json

问题描述

我正在尝试通过 API 将数据发布到 InsightVM。我不断收到错误 400,这意味着格式错误。我把它分解了,问题出在主机名部分。

 JSONObject json = new JSONObject();
 JSONArray array = new JSONArray();

  if (host_info.getDataType() == dataType.Web_Vulnerability && methodType == MethodType.Add_host_To_Site)
                {
                    JSONObject json2 = new JSONObject();
                    json2.put("name",host_info.getHost_fqdn());
                    json2.put("source", "Splunk");
                    array.add(json2);

                    DateTimeFormatter dtf = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
                    json.put("date",OffsetDateTime.now().format(dtf) );
                    json.put("ip",host_info.getHost_ip());
                    json.put("os",host_info.getOperating_system());
                    json.put("hostNames",array); // problem is here 
                }

上面的代码是否提供与以下相同的格式:

{

"date": "2019-05-20",
"ip": "00.00.00.00",
"os":"Linux",
"hostNames": 
[
{
"name": "corporate-workstation-1102DC.acme.com",
"source": "Splunk"
}
]

}

标签: jsonpostman

解决方案


JSONArray 实现集合。
虽然 JSONObject 有一个重载的 put() 方法,
它接受一个 Collection 并将其包装在一个 JSONArray 中,这可能会导致问题。
你可以试试以下 -

jsonObject.put("hostNames",(Object)array);

推荐阅读