DEV Community

Cover image for Querying and validating a JSON document in Java
JJBRT
JJBRT

Posted on • Edited on

Querying and validating a JSON document in Java

The JSON format is now the standard for communication between distributed services and there are various solutions for reading and validating these documents: here we will present a new one compatible with the latest Java versions: the Burningwave JSON library.

To start we need to add the following dependency to our pom.xml:

<dependency>
    <groupId>org.burningwave</groupId>
    <artifactId>json</artifactId>
    <version>0.13.0</version>
</dependency>

To use Burningwave JSON as a Java module, add the following to your module-info.java:

requires org.burningwave.json;

HitCount

In this library there are 3 types of objects that respectively deal with reading, querying and validating JSON documents:

To explain how these types of objects work we will take the following JSON document as input:

{
"quiz": {
"sport": {
"q1": {
"question": "Which one is correct team name in NBA?",
"options": [
"New York Bulls",
"Los Angeles Kings",
"Golden State Warriros",
"Huston Rocket"
],
"answer": "Huston Rocket"
}
},
"maths": {
"q1": {
"question": "5 + 7 = ?",
"options": [
"10",
"11",
"12",
"13"
],
"answer": "12"
},
"q2": {
"question": "12 - 8 = ?",
"options": [
"1",
"2",
"3",
"4"
],
"answer": "4"
}
}
}
}
view raw quiz.json hosted with ❤ by GitHub

The ObjectHandler

First of all, to find values in a JSON document we need to load it via ObjectHandler. The ObjectHandler wraps the JSON document and contains the path and the value of the node you are visiting within the JSON. To instantiate an ObjectHandler follow this code:

Facade facade = Facade.create();
//Loading the JSON object
ObjectHandler objectHandler = facade.newObjectHandler(
ObjectHandlerTest.class.getClassLoader().getResourceAsStream("quiz.json"),
Root.class
);

The Finder

After loaded the JSON document, to search elements within it we need to instantiate a Finder. There are 3 kinds of Finder:

The ObjectHandler.Finder

To obtain this kind of finder we need to use this code:

ObjectHandler.Finder finder = objectHandler.newFinder();

Once we obtained the finder we can use it to search items inside the JSON document:

//Searching for the first occurrence by path suffix
ObjectHandler sportOH = finder.findFirstForPathEndsWith("sport");
//Retrieving the path of the sport object ("quiz.sport")
String sportPath = sportOH.getPath();
//Retrieving the value of the sport object
Sport sport = sportOH.getValue();
ObjectHandler option2OfSportQuestionOH = finder.findFirstForPathEndsWith(Path.of("sport", "q1", "options[1]"));
String option2OfSportQuestionOHPath = option2OfSportQuestionOH.getPath();
String option2OfSportQuestion = option2OfSportQuestionOH.getValue();
ObjectHandler questionOneOH = finder.findForPathEquals(Path.of("quiz", "sport", "q1"));
String questionOnePath = questionOneOH.getPath();
Question questionOne = questionOneOH.getValue();

The ObjectHandler.ValueFinder

To obtain this kind of finder we need to use this code:

ObjectHandler.Finder finder = objectHandler.newValueFinder();

Once we obtained the finder we can use it to search items inside the JSON document:

//Searching for the first occurrence by path suffix
Sport sport = finder.findFirstForPathEndsWith("sport");
String option2OfSportQuestion = finder.findFirstForPathEndsWith(Path.of("sport", "q1", "options[1]"));
Question questionOne = finder.findForPathEquals(Path.of("quiz", "sport", "q1"));

The ObjectHandler.ValueFinderAndConverter

To obtain this kind of finder we need to use this code:

ObjectHandler.Finder finderAndConverter = objectHandler.newValueFinderAndConverter();

Once you obtained the finder we can use it to search items inside the JSON document and convert them:

//Searching for the first occurrence by path suffix and convert it
Map<String, Object> sportAsMap = finderAndConverter.findFirstForPathEndsWith("sport");

The Validator

To validate a JSON document we need to obtain the Validator and then register the checks:

facade.validator().registerCheck(
//Checking whether a value in any field marked as required
//(e.g.: @JsonProperty(value = "answer", required = true)) is null
Check.forAll().checkMandatory(),
//Checking whether a string value in any field is empty
Check.forAllStringValues().execute(pathValidationContext -> {
if (pathValidationContext.getValue() != null && pathValidationContext.getValue().trim().equals("")) {
pathValidationContext.rejectValue("IS_EMPTY", "is empty");
}
})
);

Once registered the checks, to execute the validation you must call the validate method:

Collection<Throwable> exceptions =
facade.validator().validate(
Validation.Config.forJsonObject(objectHandler.getValue())
//By calling this method the validation will be performed on the entire document,
//otherwise the validation will stop at the first exception thrown
.withCompleteValidation()
);

The search and validation possibilities offered by this library are practically infinite and this tutorial only shows an overview of the components exposed by the library and some examples of basic operation: for any further help you can open a discussion on GitHub.

From here you can download/clone the tutorial shared on GitHub.

Retry later

Top comments (0)

Retry later
Retry later