@jsonview在未知属性上失败

时间:2016-03-28 13:19:40

标签: java spring jackson objectmapper

我需要在反序列化时使用@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;
}

我需要实现的是,如果我想创建一个Person,我只需要传递'personName'。如果我传递'companyName',我需要抛出异常。如何使用@JsonView实现这一目标?还有其他选择吗?

1 个答案:

答案 0 :(得分:1)

我认为@JsonView不足以为您解决这个问题。以下是更多信息:UnrecognizedPropertyException is not thrown when deserializing properties that are not part of the view

但我只是看了一下源代码,并设法有点" hack"这个问题与@JsonView和自定义BeanDeserializerModifier相结合。它并不漂亮,但这是必不可少的部分:

public static class MyBeanDeserializerModifier extends BeanDeserializerModifier {

    @Override
    public BeanDeserializerBuilder updateBuilder(DeserializationConfig config, 
                     BeanDescription beanDesc, BeanDeserializerBuilder builder) {
        if (beanDesc.getBeanClass() != Contact.class) {
            return builder;
        }

        List<PropertyName> properties = new ArrayList<>();
        Iterator<SettableBeanProperty> beanPropertyIterator = builder.getProperties();
        Class<?> activeView = config.getActiveView();


        while (beanPropertyIterator.hasNext()) {
            SettableBeanProperty settableBeanProperty = beanPropertyIterator.next();
            if (!settableBeanProperty.visibleInView(activeView)) {
                properties.add(settableBeanProperty.getFullName());
            }
        }

        for(PropertyName p : properties){
            builder.removeProperty(p);
        }

        return builder;
    }
}

以下是在对象映射器上注册的方法:

ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.setDeserializerModifier(new MyBeanDeserializerModifier());
mapper.registerModule(module);

这适用于我,我现在收到UnrecognizedPropertyException:

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "companyName" (class Main2$Contact), not marked as ignorable (one known property: "personName"])