@jsonview在未知属性上失败

vm0i2vca  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(350)

我需要使用@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实现这一点?有别的选择吗?

b5buobof

b5buobof1#

我想 @JsonView 不足以解决这个问题。以下是详细信息:当反序列化不属于视图的属性时,不会引发UnrecognedPropertyException
但我只是查看了源代码,并设法结合 @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;
    }
}

下面是如何在对象Map器上注册它:

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

这对我很有效,我现在遇到了无法识别的属性异常:

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

相关问题