JSON Schema Validation example in java

Posted on

Validating input is a good programming practice than spending times to trying to guard each line of codes against all the way the input goes wrong.

This is especially true when we are writing a web service that deal with input data of a PUT,POST,DELETE and GET method with MIME type JavaScript Object Notation (JSON) .  JSON data is formatted as a key & value pair and each key & value represent a properties name and value separated by the colon (:).

In last post, we have seen the Jackson framework that is used to marshaling and unmarshalling the JSON data to Java object and vice-versa, But validating JSON data is another task, unfortunately Jackson framework does not  provide to do validate JSON data.

json-schema-validator available at https://github.com is quite popular with Java developer to validate JSON data against Schema file.

JSON schema is:

  • A way of describing your existing data format
  • Written in clear, human and machine readable, documentation
  • Complete structural validation useful for
    • Automated testing
    • Validating client submitted data

Look at the below Schema file. This schema file exactly tells, in Input JSON data , “id” must be String type, “amount” properties must be any Number type and “Currency” must be out of four currency else throw validation exception. As you can created own Schema file base on the incoming input date.

 

trade-schema.json under /src/main/resources/schema folder

{
  "title": "Daily Trade Transaction",
  "description": "Daily Trade Transaction",
  "type": "object",
  "properties": {
    "id":{
      "type":"string"
    },
    "amount":{
      "type":"number"
    },
    "currency":{
      "type":"string",
      "enum":["INR", "HKD", "EUR", "USD"]
    }
  }
}

ref link:-
http://json-schema.org/examples.html
validate Schema online :-
http://json-schema-validator.herokuapp.com/

Let’s build a simple Application :-

trade.json :- Input data store in a file.

id,amount,currency
"1001",10000045.999,"EUR"
"1002",17777045.999,"HKD"
"1003",10000045.999,"USD"
"1004",1234045.999,"EUR"
"1005",100875.999,"HKD"
"1006",165780045.999,"EUR"
"1007",32452345.999,"INR"
"1008",7777777.999,"EUR"

 

JsonSchemaManager.Java : Used to validate all Java Object with specific Schema.


package com.example.utilities;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.RuntimeJsonMappingException;
import com.github.fge.jackson.JsonLoader;
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;
import com.google.common.collect.Lists;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static javafx.scene.input.KeyCode.J;

/**
 * Created by MYPC on 7/17/2016.
 */
public class JsonSchemaManager {
    private final JsonValidator validator = JsonSchemaFactory.byDefault().getValidator();
    private Map<Class<?>, JsonNode> jsonNodeMap = new HashMap<>();

    public void load(Class<?> className, String schema) throws IOException {
        JsonNode schemaFromDisk = JsonLoader.fromURL(this.getClass().getResource(schema));
        jsonNodeMap.put(className, schemaFromDisk);
    }

    public void check(Class<?> className, JsonNode toBeValidate) {

        ProcessingReport report = null;
        try {
            report = validator.validate(jsonNodeMap.get(className), toBeValidate);
            if (!report.isSuccess()) {
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append(" Oops!! failed JSON validation ");
                stringBuilder.append(":").append("\n");
                List messages = Lists.newArrayList(report);

                for (int i = 0; i < messages.size(); i++) { stringBuilder.append("- "); stringBuilder.append(messages.get(i).toString()); stringBuilder.append((i == (messages.size()) - 1) ? "" : "\r"); } throw new RuntimeException(stringBuilder.toString()); } } catch (ProcessingException e) { throw new RuntimeJsonMappingException("ERROR -->" + e.toString());
        }
    }
}

Main Class that validate the JSON data.


package com.example;

import com.example.model.Transaction;
import com.example.service.CSVReader;
import com.example.utilities.JsonSchemaManager;
import com.fasterxml.jackson.databind.JsonNode;

import java.io.IOException;
import java.util.List;

/**
 * Created by MYPC on 7/18/2016.
 */
public class JSONSchemaReaderApp {

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

        JsonSchemaManager jsonSchemaManager = new JsonSchemaManager();
        CSVReader csvReader = new CSVReader();
        // Load schema file from resource folder.
        jsonSchemaManager.load(Transaction.class, "/schema/trade-schema.json");
        // Load JSON data from file system and convert into JsonNode Object
        List lists = csvReader.load(Transaction.class, JSONSchemaReaderApp.class.getClassLoader().getResource("trade.csv"));
        for (int i = 0; i < lists.size(); i++) {
            //validate each JsonNode of Type Transaction to Schema file.
            jsonSchemaManager.check(Transaction.class, lists.get(i));
            lists.get(i);
        }
    }
}

complete src download here

Thanks

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s