我收到一个 json 编码的字符串,然后将其解码为 pojo,如下所示:
String json = ...
final ObjectMapper mapper = new ObjectMapper();
MyPojo obj = mapper.readValue(json, MyPojo.class);
我希望能够验证此输入,但我不确定这样做的“正确方法”是什么。
假设 MyPojo 是这样定义的:
@JsonIgnoreProperties(ignoreUnknown=true)
class MyPojo {
public static enum Type {
One,
Two,
Three;
@JsonValue
public String value() {
return this.name().toLowerCase();
}
}
private String id;
private Type type;
private String name;
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
public Type getType() {
return this.type;
}
public void setType(Type type) {
this.type = type;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
我想验证三件事:
- 所有成员都有值(value)观
- 枚举值是枚举的一部分
- 根据某些标准(即:最小或最大长度、最小或人数值、正则表达式等)测试部分或所有值
如果验证失败,我想返回一条有意义且可读的消息。
对于第一个和第三个问题,我可以简单地检查对象的所有成员,看看是否有任何成员为空,如果没有则根据条件测试它们,但是当有很多字段时,这种方法会变得冗长和复杂。
至于第二个问题,如果输入中的值与枚举值之一不匹配,则会抛出 JsonMappingException
,因此我设法做到了这一点:
try {
MyPojo obj = mapper.readValue(json, MyPojo.class);
}
catch (JsonMappingException e) {
return "invalid value for property: " + e.getPath().get(0).getFieldName();
}
但是我如何获取输入中的值以便返回:无效值:属性的值:PROPERTY
?
谢谢。
最佳答案
我建议使用 JSR-303 Bean Validation 的实现.该规范定义了一组注释和 XML 配置文件,用于指定您希望在域对象上验证的约束。引用实现可在此处获得:
关于java - 使用 jackson 解码 json 时的验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11362104/