杰克逊@JsonProperty(required = true)不会抛出异常

我正在使用jackson 2.2批注@JsonProperty,并将required设置为true。通过ObjectMapper

readValue()方法反序列化不包含该属性的json文件时,不会引发异常。它应该以其他方式工作还是我错过了什么?

我的DTO课程:

public class User {

public enum Gender {MALE, FEMALE}

;

public static class Name {

private String _first, _last;

public String getFirst() {

return _first;

}

public String getLast() {

return _last;

}

public void setFirst(String s) {

_first = s;

}

public void setLast(String s) {

_last = s;

}

}

private Gender _gender;

private Name _name;

private boolean _isVerified;

private byte[] _userImage;

@JsonProperty(value ="NAAME",required = true)

public Name getName() {

return _name;

}

@JsonProperty("VERIFIED")

public boolean isVerified() {

return _isVerified;

}

@JsonProperty("GENDER")

public Gender getGender() {

return _gender;

}

@JsonProperty("IMG")

public byte[] getUserImage() {

return _userImage;

}

@JsonProperty(value ="NAAME",required = true)

public void setName(Name n) {

_name = n;

}

@JsonProperty("VERIFIED")

public void setVerified(boolean b) {

_isVerified = b;

}

@JsonProperty("GENDER")

public void setGender(Gender g) {

_gender = g;

}

@JsonProperty("IMG")

public void setUserImage(byte[] b) {

_userImage = b;

}

}

这是我如何反序列化类:

public class Serializer {

private ObjectMapper mapper;

public Serializer() {

mapper = new ObjectMapper();

SimpleModule sm = new SimpleModule("PIF deserialization");

mapper.registerModule(sm);

}

public void writeUser(File filename, User user) throws IOException {

mapper.writeValue(filename, user);

}

public User readUser(File filename) throws IOException {

return mapper.readValue(filename, User.class);

}

}

实际上是这样的:

    Serializer serializer = new Serializer();

User result = serializer.readUser(new File("user.json"));

Actuall json看起来像:

{"GENDER":"FEMALE","VERIFIED":true,"IMG":"AQ8="}

我希望这是因为json文件中未指定_name,并且要求抛出该异常。

回答:

按照Jackson注释javadocs的说明:“请注意,从2.0版本开始,BeanDeserializer不使用此属性:期望为更高的次要版本添加支持。”

也就是说:使用此设置不会执行任何验证。它仅(当前)用于生成JSON模式,或用于自定义代码。

以上是 杰克逊@JsonProperty(required = true)不会抛出异常 的全部内容, 来源链接: utcz.com/qa/433016.html

回到顶部