Java 使用jackson解码json时的验证
我收到一个json编码的字符串,然后将其解码为pojo,如下所示:Java 使用jackson解码json时的验证,java,json,jackson,Java,Json,Jackson,我收到一个json编码的字符串,然后将其解码为pojo,如下所示: String json = ... final ObjectMapper mapper = new ObjectMapper(); MyPojo obj = mapper.readValue(json, MyPojo.class); @JsonIgnoreProperties(ignoreUnknown=true) class MyPojo { public static enum Type { O
String json = ...
final ObjectMapper mapper = new ObjectMapper();
MyPojo obj = mapper.readValue(json, MyPojo.class);
@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;
}
}
我希望能够验证此输入,但我不确定“正确方式”是什么。假设MyPojo的定义如下:
String json = ...
final ObjectMapper mapper = new ObjectMapper();
MyPojo obj = mapper.readValue(json, MyPojo.class);
@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
,因此我设法做到了这一点:
try {
MyPojo obj = mapper.readValue(json, MyPojo.class);
}
catch (JsonMappingException e) {
return "invalid value for property: " + e.getPath().get(0).getFieldName();
}
但是如何在输入中获取值,以便返回:无效值:property的值:property
谢谢。我建议使用的实现。此规范定义了一组注释和XML配置文件,用于指定要在域对象上验证的约束。此处提供了参考实施: