Prateek Narendra
Prateek Narendra

Reputation: 1937

Check is JSON is a valid Swagger or not

I have a javax.json.Json object which I need to validate if its a valid Swagger file or not. I wrote these utility functions -

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;
    }

}

However, I see that even with an invalid Swagger file, i get an evaluation of true. Is there any way I can check if a Swagger is valid or not?

Upvotes: 1

Views: 768

Answers (1)

Mark
Mark

Reputation: 5239

You might be able to use SwaggerParser#readWithInfo which returns a SwaggerDeserializationResult object, when an error occurs they fill the List<String> messages of that object with a specific message:

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");

You can check for these sentences and make sure it's none of those, this should mean that it successfully parsed.


SwaggerDeserializationResult swagger = new SwaggerParser().readWithInfo(myJSONString);
List<String> messages = swagger.getMessages();

// Check if messages contains any of those strings

Upvotes: 1

Related Questions