Tenable API JSON请求集成报错:JSONArray格式异常求助
问题修复方案
1. 解决JSONArray解析错误
错误栈显示getUUID方法第141行将非数组JSON解析为JSONArray,这是因为该方法请求返回的是JSON对象(以{开头),而非JSON数组(以[开头)。
打开getUUID方法,找到类似以下的错误代码:
String response = ...; // 从请求获取的响应字符串 JSONArray jsonArray = new JSONArray(response); // 错误行
将其改为用JSONObject解析:
String response = ...; JSONObject jsonObject = new JSONObject(response); // 根据实际返回结构提取uuid,示例: String uuid = jsonObject.getString("uuid");
2. 修复请求体的JSON格式错误
你用String.format拼接的JSON存在多处语法错误,直接拼接字符串极易出错,建议用org.json库API构建JSON,彻底避免格式问题:
核心错误点:
settings是配置对象,需用{}包裹,而非数组符号[]credentials是键值对结构,不能放在数组[]中(多凭证场景才用数组)assets的写法非法,数组内必须是完整对象,不能直接写"asset": 值
修复后的请求体构建代码:
// 构建settings配置对象 JSONObject settings = new JSONObject(); settings.put("name", scanName); settings.put("policy", policyName); settings.put("scan_zone", scanZone); settings.put("import_repositories", importRepository); settings.put("starttime", "now"); // 构建credentials凭证对象 JSONObject credentials = new JSONObject(); credentials.put("category", credentialsCategory); credentials.put("name", credentialsName); settings.put("credentials", credentials); // 单凭证直接放对象,多凭证则用JSONArray // 构建assets资产数组 JSONArray assetsArray = new JSONArray(); for (String asset : assetsList) { JSONObject assetObj = new JSONObject(); assetObj.put("asset", asset); assetsArray.put(assetObj); } settings.put("assets", assetsArray); // 组装完整请求体 JSONObject requestBody = new JSONObject(); requestBody.put("uuid", getUUID(baseUrl, httpClient)); requestBody.put("settings", settings); // 转换为JSON字符串 String requestJson = requestBody.toString();
替换原请求体代码
把原来用String.format拼接requestBody的逻辑,替换为上述代码,然后设置请求实体:
httpPost.setEntity(new StringEntity(requestJson, StandardCharsets.UTF_8));
3. 验证合法JSON格式
修复后,请求体应符合以下合法结构(可根据Tenable SC API细节微调):
{ "uuid": "xxx-xxx-xxx", "settings": { "name": "zTestScan1", "policy": "Full scan including web", "scan_zone": "Default Scan Zone", "import_repositories": "Active Vulns", "credentials": { "category": "Windows", "name": "NessusScan" }, "assets": [ {"asset": "asset1"}, {"asset": "asset2"} ], "starttime": "now" } }
内容的提问来源于stack exchange,提问作者Code4Security
相关产品推荐
相关产品推荐

