【问题标题】:Jackson @JsonView annotation interferes with VisibilityJackson @JsonView 注释干扰了可见性
【发布时间】:2018-06-18 11:35:50
【问题描述】:

我有以下测试设置:

public class TestingPojo {

    public int getA() {
        return 1;
    }

    @JsonView(Trimmed.class)
    private String getProperty() {
        return "viewproperty"; // should not be included in "default" serialization without writer view
    }
}

@Test
public void testTrimmed() throws JsonProcessingException {

    String result = getMapper().writerWithView(Trimmed.class).writeValueAsString(new TestingPojo());

    Assert.assertFalse(result.contains("1"));
    Assert.assertTrue(result.contains("viewproperty"));
}

@Test
public void testUntrimmed() throws JsonProcessingException {

    String result = getMapper().writeValueAsString(new TestingPojo());

    Assert.assertTrue(result.contains("1"));
    Assert.assertFalse(result.contains("viewproperty")); // this should not be included as it is a private getter and @JsonView trimmed only
}

private ObjectMapper getMapper() {

    ObjectMapper mapper = new ObjectMapper();
    mapper.setVisibility(PropertyAccessor.GETTER, Visibility.PUBLIC_ONLY);
    mapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false);

    return mapper;
}

我的“testTrimmed()”工作正常,输出中只包含“viewproperty”,因为序列化是使用Trimmed.class 视图执行的。

问题是“testUntrimmed()”没有按预期工作,因为“1”按预期包含但“viewproperty”也包含在序列化输出中,即使我已明确设置ObjectMapper应该仅对公共 getter 进行序列化(并且 getProperty() 是私有的)。问题还在于,如果我删除“testUntrimmed()”的 @JsonView 注释,则此测试将按预期工作。

这是@JsonView 的问题还是我做错了什么/我可以做些什么来防止@JsonView 带注释的getter 在不提供writer-view 的情况下被序列化到结果中?

默认视图包含也已关闭。

我的结论:私有 @JsonView 带注释的 getter 包含在序列化中而不提供视图这一事实对我来说似乎是一个明显的杰克逊错误

【问题讨论】:

    标签: java serialization jackson


    【解决方案1】:

    就像你说的,当你删除“testUntrimmed()”的@JsonView 时,它会没事的,那为什么会这样呢?如果您检查以下源代码,那么您会找到原因(@JsonView 将使 VisibilityChecker 不起作用。):

    //com.fasterxml.jackson.databind.introspect.POJOPropertiesCollector#_addGetterMethod

    protected void _addGetterMethod(Map<String, POJOPropertyBuilder> props,
            AnnotatedMethod m, AnnotationIntrospector ai)
    {
        // Very first thing: skip if not returning any value
        if (!m.hasReturnType()) {
            return;
        }
    
        // any getter?
        if (ai != null) {
            if (ai.hasAnyGetterAnnotation(m)) {
                if (_anyGetters == null) {
                    _anyGetters = new LinkedList<AnnotatedMember>();
                }
                _anyGetters.add(m);
                return;
            }
            // @JsonValue?
            if (ai.hasAsValueAnnotation(m)) {
                if (_jsonValueGetters == null) {
                    _jsonValueGetters = new LinkedList<AnnotatedMethod>();
                }
                _jsonValueGetters.add(m);
                return;
            }
        }
        String implName; // from naming convention
        boolean visible;
    
        PropertyName pn = (ai == null) ? null : ai.findNameForSerialization(m);
        boolean nameExplicit = (pn != null);
    
        if (!nameExplicit) { // no explicit name; must consider implicit
            implName = (ai == null) ? null : ai.findImplicitPropertyName(m);
            if (implName == null) {
                implName = BeanUtil.okNameForRegularGetter(m, m.getName(), _stdBeanNaming);
            }
            if (implName == null) { // if not, must skip
                implName = BeanUtil.okNameForIsGetter(m, m.getName(), _stdBeanNaming);
                if (implName == null) {
                    return;
                }
                visible = _visibilityChecker.isIsGetterVisible(m);
            } else {
                visible = _visibilityChecker.isGetterVisible(m);
            }
        } else { // explicit indication of inclusion, but may be empty
            // we still need implicit name to link with other pieces
            implName = (ai == null) ? null : ai.findImplicitPropertyName(m);
            if (implName == null) {
                implName = BeanUtil.okNameForGetter(m, _stdBeanNaming);
            }
            // if not regular getter name, use method name as is
            if (implName == null) {
                implName = m.getName();
            }
            if (pn.isEmpty()) {
                // !!! TODO: use PropertyName for implicit names too
                pn = _propNameFromSimple(implName);
                nameExplicit = false;
            }
            visible = true;
        }
        boolean ignore = (ai == null) ? false : ai.hasIgnoreMarker(m);
        _property(props, implName).addGetter(m, pn, nameExplicit, visible, ignore);
    }
    

    //com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector#findNameForSerialization

    @Override
    public PropertyName findNameForSerialization(Annotated a)
    {
        String name = null;
    
        JsonGetter jg = _findAnnotation(a, JsonGetter.class);
        if (jg != null) {
            name = jg.value();
        } else {
            JsonProperty pann = _findAnnotation(a, JsonProperty.class);
            if (pann != null) {
                name = pann.value();
                /* 22-Apr-2014, tatu: Should figure out a better way to do this, but
                 *   it's actually bit tricky to do it more efficiently (meta-annotations
                 *   add more lookups; AnnotationMap costs etc)
                 */
            } else if (_hasAnnotation(a, JsonSerialize.class)
                    || _hasAnnotation(a, JsonView.class)
                    || _hasAnnotation(a, JsonRawValue.class)
                    || _hasAnnotation(a, JsonUnwrapped.class)
                    || _hasAnnotation(a, JsonBackReference.class)
                    || _hasAnnotation(a, JsonManagedReference.class)) {
                name = "";
            } else {
                return null;
            }
        }
        return PropertyName.construct(name);
    }
    

    也许你可以使用@JsonFilter 来实现你的要求..只是一个建议..演示代码:

    @JsonFilter("myFilter")
    public class TestingPojo{
    public int getA()
    {
        return 1;
    }
    
    @JsonView(Trimmed.class)
    private String getProperty()
    {
        return "viewproperty"; // should not be included in "default" serialization without writer view
    }
    
    interface Trimmed {}
    
    @Test
    public void testTrimmed() throws JsonProcessingException
    {
        SimpleFilterProvider filterProvider = new SimpleFilterProvider();
        filterProvider.addFilter("myFilter",SimpleBeanPropertyFilter.serializeAll());
        String result = getMapper().writer(filterProvider).withView(Trimmed.class)
                                   .writeValueAsString(new TestingPojo());
    
        Assert.assertFalse(result.contains("1"));
        Assert.assertTrue(result.contains("viewproperty"));
    }
    
    @Test
    public void testUntrimmed() throws JsonProcessingException
    {
        SimpleFilterProvider filterProvider = new SimpleFilterProvider();
        filterProvider.addFilter("myFilter",SimpleBeanPropertyFilter.serializeAllExcept("property"));
        String result = getMapper().writer(filterProvider).writeValueAsString(new TestingPojo());
    
        Assert.assertTrue(result.contains("1"));
        Assert.assertFalse(result.contains("viewproperty")); // this should not be included as it is a private getter and @JsonView trimmed only
    }
    
    private ObjectMapper getMapper()
    {
    
        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(
                PropertyAccessor.GETTER,
                JsonAutoDetect.Visibility.PUBLIC_ONLY
        );
        mapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION,
                         false);
    
        return mapper;
    } 
    }
    

    【讨论】:

    • 过滤有效,谢谢 -> 但是这对我来说并不是一个真正可行的解决方案,因为我必须手动排除 30 多个属性。
    • 那么也许自定义 JsonSerializer 或自定义 com.fasterxml.jackson.databind.AnnotationIntrospector 更适合你
    • 如果是后者,你可以简单地覆盖方法 findNameForSerialization
    猜你喜欢
    • 2019-10-27
    • 1970-01-01
    • 2020-04-01
    • 1970-01-01
    • 2019-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-03
    相关资源
    最近更新 更多