I have a json string and two different classes with different properties. Classes looks like this:
studentId
name
surname
gpa
Getters/Setters
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);
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;
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With