2

我需要使用@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;
}

我需要实现的是,如果我想创建一个人,我只需要传递“人名”。如果我通过'companyName',我需要抛出异常。如何使用@JsonView 实现这一目标?有没有其他选择?

4

1 回答 1

1

我认为@JsonView不足以为您解决这个问题。以下是更多信息原因:反序列化不属于视图的属性时不会抛出 UnrecognizedPropertyException

但是我只是查看了源代码并设法通过组合@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"])
于 2016-03-28T18:57:28.513 回答