有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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) 个答案

  1. # 1 楼答案

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

    但我只是查看了源代码,并设法结合@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);
    

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

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