Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

json

jackson

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); 
like image 753
brainmassage Avatar asked Feb 25 '16 10:02

brainmassage


2 Answers

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;
        } 

    }
like image 72
Yusuf K. Avatar answered Nov 03 '22 11:11

Yusuf K.


The fastest way to achieve that would be with trial and error :

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

but i strongly suggest to deal with the problem in a more structured way, i.e. try not to rely on trial and error.

like image 44
francesco foresti Avatar answered Nov 03 '22 11:11

francesco foresti