java - Jackson @JsonView 注释会干扰可见性

标签 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 View 执行的。

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

这是 @JsonView 的问题吗?还是我做错了什么/我能做些什么来防止 @JsonView 带注释的 getter 在不提供作者观点?

默认 View 包含也已关闭。

我的结论:私有(private) @JsonView 带注释的 getter 包含在序列化中而不提供 View 这一事实对我来说似乎是一个明显的 jackson 错误

最佳答案

就像你说的,当你删除“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;
} 
}

关于java - Jackson @JsonView 注释会干扰可见性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50908608/

相关文章:

java - 如何在 fragment 中放置或替换列表

java - 从 Android 应用程序登录使用 HTTP 基本身份验证的网站

java - 使用 Java 创建一个 plist

java - 如何使用 Jackson 正确序列化/反序列化 java.time.DayOfWeek?

java - 如何使用标准 setter 反序列化 JSON 字符串

java - 无限循环,不会以while循环结束

java - Java 的 XMLEncoder 可以序列化具有不可序列化字段的对象吗?

java - JVM 和私有(private)方法

java - 如何防止 CsvMapper 在输出 CSV 中包含无法识别的字段?

java - 这个 Java 错误消息意味着什么?我该如何解决它?