Thursday, 8 April 2021

Extract all messages from processing report in json-schema validator

Following snippet is used to print ProcessingReport.

public static void printProcessingReport(ProcessingReport processingReport) {
  Iterator<ProcessingMessage> itr = processingReport.iterator();

  while (itr.hasNext()) {
    ProcessingMessage message = itr.next();
    System.out.println(message.asJson().toPrettyString());

    JsonNode messageNode = message.asJson().get("message");

    if (messageNode != null) {
      System.out.println("Message " + messageNode.asText() + "\n\n");
    }

  }
}

 

Find the below working application.

 

JsonSchemaUtil.java

 

package com.sample.app.util;

import java.util.Iterator;
import java.util.Map;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.module.jsonSchema.JsonSchema;
import com.fasterxml.jackson.module.jsonSchema.JsonSchemaGenerator;
import com.github.fge.jsonschema.core.exceptions.ProcessingException;
import com.github.fge.jsonschema.core.report.ProcessingMessage;
import com.github.fge.jsonschema.core.report.ProcessingReport;
import com.github.fge.jsonschema.main.JsonSchemaFactory;
import com.github.fge.jsonschema.main.JsonValidator;

public class JsonSchemaUtil {
  private static final JsonValidator VALIDATOR = JsonSchemaFactory.byDefault().getValidator();
  private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

  public static String getJsonSchema(Class<?> type) throws JsonProcessingException {
    JsonSchemaGenerator schemaGen = new JsonSchemaGenerator(OBJECT_MAPPER);
    JsonSchema schema = schemaGen.generateSchema(type);
    String schemaString = OBJECT_MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(schema);
    return schemaString;
  }

  public static ProcessingReport validateJson(String jsonDocument, String jsonSchema)
      throws JsonMappingException, JsonProcessingException, ProcessingException {
    Map<String, Object> jsonPayloadMap = OBJECT_MAPPER.readValue(jsonDocument,
        new TypeReference<Map<String, Object>>() {
        });
    JsonNode jsonPayloadNode = OBJECT_MAPPER.convertValue(jsonPayloadMap, JsonNode.class);

    Map<String, Object> jsonSchemaMap = OBJECT_MAPPER.readValue(jsonSchema,
        new TypeReference<Map<String, Object>>() {
        });
    JsonNode jsonSchemaNode = OBJECT_MAPPER.convertValue(jsonSchemaMap, JsonNode.class);

    return VALIDATOR.validate(jsonSchemaNode, jsonPayloadNode);
  }

  public static void printProcessingReport(ProcessingReport processingReport) {
    Iterator<ProcessingMessage> itr = processingReport.iterator();

    while (itr.hasNext()) {
      ProcessingMessage message = itr.next();
      System.out.println(message.asJson().toPrettyString());

      JsonNode messageNode = message.asJson().get("message");

      if (messageNode != null) {
        System.out.println("Message " + messageNode.asText() + "\n\n");
      }

    }
  }
}

 

App.java

package com.sample.app;

import java.io.IOException;

import com.github.fge.jsonschema.core.exceptions.ProcessingException;
import com.github.fge.jsonschema.core.report.ProcessingReport;
import com.sample.app.util.JsonSchemaUtil;

public class App {

  public static void main(String args[]) throws IllegalArgumentException, IOException, ProcessingException {

    String jsonPayload = "{\"id\":false,\"name\":\"Krishna\",\"age\":true,\"address\":{\"street\":\"Chowdeswari\",\"city\":\"Bangalore\",\"country\":\"India\"}}";

    String jsonSchema = "{\"type\":\"object\",\"properties\":{\"id\":{\"type\":\"number\"},\"name\":{\"type\":\"string\"},\"age\":{\"type\":\"number\"},\"address\":{\"type\":\"object\",\"properties\":{\"street\":{\"type\":\"string\"},\"city\":{\"type\":\"string\"},\"country\":{\"type\":\"string\"}}}}}";

    ProcessingReport processingReport = JsonSchemaUtil.validateJson(jsonPayload, jsonSchema);

    if (processingReport.isSuccess()) {
      System.out.println("Valid json document against json schema");
      System.exit(0);
    }
    
    JsonSchemaUtil.printProcessingReport(processingReport);

    
  }

}

 

Output

{
  "level" : "error",
  "schema" : {
    "loadingURI" : "#",
    "pointer" : "/properties/age"
  },
  "instance" : {
    "pointer" : "/age"
  },
  "domain" : "validation",
  "keyword" : "type",
  "message" : "instance type (boolean) does not match any allowed primitive type (allowed: [\"integer\",\"number\"])",
  "found" : "boolean",
  "expected" : [ "integer", "number" ]
}
Message instance type (boolean) does not match any allowed primitive type (allowed: ["integer","number"])


{
  "level" : "error",
  "schema" : {
    "loadingURI" : "#",
    "pointer" : "/properties/id"
  },
  "instance" : {
    "pointer" : "/id"
  },
  "domain" : "validation",
  "keyword" : "type",
  "message" : "instance type (boolean) does not match any allowed primitive type (allowed: [\"integer\",\"number\"])",
  "found" : "boolean",
  "expected" : [ "integer", "number" ]
}
Message instance type (boolean) does not match any allowed primitive type (allowed: ["integer","number"])

 

 

 

 

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment