我收到一个 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;
}
}
我想验证三件事:
- 所有成员都有价值观
- 枚举值是枚举的一部分
- 根据某些标准测试部分或全部值(即:最小或最大长度、最小或人数值、正则表达式等)
如果验证失败,我想返回一个有意义且可读的消息。
对于第一个和第三个问题,我可以简单地检查对象的所有成员,看看是否有任何成员为空,如果不根据标准测试它们,但是当有很多字段时,这种方法会变得冗长而复杂。
至于第二个问题,如果输入中的值与枚举值之一不匹配,JsonMappingException
则抛出 a,因此我设法做到了:
try {
MyPojo obj = mapper.readValue(json, MyPojo.class);
}
catch (JsonMappingException e) {
return "invalid value for property: " + e.getPath().get(0).getFieldName();
}
但是如何获取输入中的值以便我可以返回:invalid value: VALUE for property: PROPERTY
?
谢谢。