json - 如 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"
}
]
}
解决方案
JSONArray 实现集合。
虽然 JSONObject 有一个重载的 put() 方法,
它接受一个 Collection 并将其包装在一个 JSONArray 中,这可能会导致问题。
你可以试试以下 -
jsonObject.put("hostNames",(Object)array);
推荐阅读
- python - python-docx如何合并行单元格
- javascript - 针对实际数据库测试 NestJS 服务
- python - 有没有什么地方可以在 VS2019 中运行 manage.py 命令行?
- javascript - 如何在角度服务之间正确共享数据
- android - 为改造模型在运行时声明多个对象
- c# - 如何在 Unity 中从服务器下载整个目录?
- python - 将数据框加入自身摘要后,数据框中的奇怪列名
- firebase - Auth Email 限制 Firebase 免费帐户中的密码重置
- jquery - jQuery 与 document.on 解除绑定?
- c++ - 如何使用接受 const int 的运算符作为 int* 优先级队列的比较器