我有一个json字符串和两个具有不同属性的不同类。类看起来像这样:
学生卡
名称
姓
加仑
获得者/设定者
TeacherId
名称
姓
获得者/设定者
现在,我得到一个json字符串,并且如果json字符串与对象模型兼容,我需要一个函数返回布尔值。
所以json可能是这样的:
{studentId: 1213, name: Mike, surname: Anderson, gpa: 3.0}
Run Code Online (Sandbox Code Playgroud)
我需要一个函数将true返还给这样的东西:
checkObjectCompatibility(json, Student.class);
Run Code Online (Sandbox Code Playgroud)
如果json字符串与类不兼容。
mapper.readValue(jsonStr, Student.class);
Run Code Online (Sandbox Code Playgroud)
方法抛出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;
}
}
Run Code Online (Sandbox Code Playgroud)