我有以下测试设置:

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应该只序列化公共获取者(并且getProperty()是私有的)。问题还在于,如果我删除“ testUntrimmed()”的@JsonView批注,则该测试将按预期工作。

这是@JsonView的问题还是我在做什么错/我该怎么做才能在没有提供writer-view的情况下防止@JsonView带注释的getter被序列化为结果?

默认视图包含也被关闭。

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

最佳答案

就像你说的那样,当你删除@JsonView的“ testUntrimmed()”时,就可以了,那为什么会这样呢?如果您检查以下源代码,那么您将找到原因(@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;
}
}

10-05 18:43