java@jsonview在未知属性上失败
我需要使用@JsonView在反序列化时抛出异常
我的POJO:
public class Contact
{
@JsonView( ContactViews.Person.class )
private String personName;
@JsonView( ContactViews.Company.class )
private String companyName;
}
我的服务:
public static Contact createPerson(String json) {
ObjectMapper mapper = new ObjectMapper().configure( DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES , true );
Contact person = mapper.readerWithView( ContactViews.Person.class ).forType( Contact.class ).readValue( json );
return person;
}
public static Contact createCompany(String json) {
ObjectMapper mapper = new ObjectMapper().configure( DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES , true );
Contact company = mapper.readerWithView( ContactViews.Company.class ).forType( Contact.class ).readValue( json );
return company;
}
我需要实现的是,如果我试图创造一个人,我只需要传递“personName”。如果我通过“companyName”,我需要抛出异常。如何使用@JsonView实现这一点?还有别的选择吗
# 1 楼答案
我认为
@JsonView
不足以为你解决这个问题。以下是更多的信息为什么:UnrecognizedPropertyException is not thrown when deserializing properties that are not part of the view但我只是查看了源代码,并设法结合
@JsonView
和定制BeanDeserializerModifier
解决了这个问题。它并不漂亮,但这里有一个重要的部分:以下是如何在对象映射器上注册它:
这对我很有效,我现在无法识别属性异常: