我有一个javax.json.Json
对象,我需要验证其是否为有效的Swagger文件。我写了这些实用程序功能-
package com.somecompany.gis.util;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonWriter;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.models.Swagger;
import io.swagger.parser.SwaggerParser;
public class Converter {
public static JsonNode toJsonNode(JsonObject jsonObject) throws IOException {
// Parse a JsonObject into a JSON string
StringWriter stringWriter = new StringWriter();
try (JsonWriter jsonWriter = Json.createWriter(stringWriter)) {
jsonWriter.writeObject(jsonObject);
}
String json = stringWriter.toString();
// Parse a JSON string into a JsonNode
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(json);
return jsonNode;
}
public static boolean isValidSwaggerSpec(JsonObject jsonObject) {
try {
JsonNode jsonNode = toJsonNode(jsonObject);
Swagger swagger = new SwaggerParser().read(jsonNode);
return true;
}catch(IOException ioe) {
return false;
}catch(Exception e) {
return false;
}
}
但是,我看到即使使用无效的Swagger文件,我也得到了true
的评估。有什么方法可以检查Swagger是否有效?
答案 0 :(得分:0)
您也许可以使用SwaggerParser#readWithInfo返回一个SwaggerDeserializationResult
对象,当发生错误时,它们会用特定的消息填充该对象的List<String> messages
:
return new SwaggerDeserializationResult().message("empty or null swagger supplied");
result = new SwaggerDeserializationResult().message("Definition does not appear to be a valid Swagger format");
return new SwaggerDeserializationResult().message("malformed or unreadable swagger supplied");
您可以检查这些句子并确保它们不存在,这意味着它已成功解析。
SwaggerDeserializationResult swagger = new SwaggerParser().readWithInfo(myJSONString);
List<String> messages = swagger.getMessages();
// Check if messages contains any of those strings