Is there a way in Jackson to check if the JSON string is compatible with POJO?

I have a json string and two different classes with different properties. The classes are as follows:

Student

studentId

name

surname

GPA

Getters / Setters

Teacher

teacherId

name

surname

Getters / Setters

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

So json might look like this:

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

I need a function returning true for something like this:

checkObjectCompatibility(json, Student.class); 
+4
source share
2 answers

if json string is incompatible with class.

mapper.readValue(jsonStr, Student.class);

throws method JsonMappingException

readValue try-catch, JsonMappingException false true.

- ;

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

        ObjectMapper mapper = new ObjectMapper();

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

    }
+3

- :

boolean isA(String json, Class expected) {
  try {
     ObjectMapper mapper = new ObjectMapper();
     mapper.readValue(json, expected);
     return true;
  } catch (JsonMappingException e) {
     e.printStackTrace();
     return false;
  } 
}

, .. .

+2

All Articles