Java – way in Jackson to check if a JSON string compatible with a POJO

jacksonjavajson

I have a json string and two different classes with different properties. Classes looks like this:

Student

studentId

name

surname

gpa

Getters/Setters

Teacher

teacherId

name

surname

Getters/Setters

Now I get a json string and I need a function to return boolean value if the json string is compatible with the object model.

So json might be like this:

{studentId: 1213, name: Mike, surname: Anderson, gpa: 3.0}

I need a function to return true to something like this:

checkObjectCompatibility(json, Student.class); 

Best Answer

if a json string is not compatible with a class.

mapper.readValue(jsonStr, Student.class);

method throws JsonMappingException

so you can create a method and call readValue method and use try-catch block to catch the JsonMappingException to return false, and otherwise return true.

Something like this;

public boolean checkJsonCompatibility(String jsonStr, Class<?> valueType) throws JsonParseException, IOException {

        ObjectMapper mapper = new ObjectMapper();

        try {
            mapper.readValue(jsonStr, valueType);
            return true;
        } catch (JsonParseException | JsonMappingException e) {
            return false;
        } 

    }