Jackson @JsonView注释会干扰Visibility

时间:2018-06-18 11:35:50

标签: java serialization jackson

我有以下测试设置:

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进行serlialize (并且getProperty()是私有的)。问题还在于,如果我删除" testUntrimmed()"的@JsonView注释。这个测试按预期工作。

这是@JsonView的问题,还是我做错了什么?如果不提供编写者视图,我该怎样做才能阻止@JsonView带注释的getter被序列化到结果中?

默认视图包含也已关闭。

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

1 个答案:

答案 0 :(得分: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;
} 
}