Spring + Jackson:如何在不使用@JsonAutoDetect注释的情况下设置类的可见性

时间:2021-12-07 18:06:11

In my spring-boot application, I have a global configuration on Jackson's ObjectMapper which told Jackson not to serialize object by fields but getters:

在我的spring-boot应用程序中,我在Jackson的ObjectMapper上有一个全局配置,它告诉Jackson不要按字段序列化对象而是getter:

@Bean
public Jackson2ObjectMapperBuilder objectMapperBuilder()
{
    return new Jackson2ObjectMapperBuilder()
    {

        @Override
        public void configure(ObjectMapper objectMapper)
        { 
            super.configure(objectMapper);
            objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
            objectMapper.setVisibility(PropertyAccessor.FIELD, Visibility.NONE);
            objectMapper.setVisibility(PropertyAccessor.GETTER, Visibility.PUBLIC_ONLY);
            objectMapper.setVisibility(PropertyAccessor.IS_GETTER, Visibility.PUBLIC_ONLY);

        }

    };
}

However, now I'm dealing with a special case. I need to serialize a class which is not written by myself (a class form dependnecy library). Since the class does not declared getters, Jackson will ignore those fields. Here's how the external class look like:

但是,现在我正在处理一个特例。我需要序列化一个不是我自己编写的类(一个类表单依赖库)。由于该课程没有宣布吸气者,杰克逊将忽略这些领域。以下是外部类的外观:

public class DirectionsResult 
{
  public GeocodedWaypoint geocodedWaypoints[];
  public DirectionsRoute routes[];
}

Although using @JsonAutoDetect annotation can customerize a class's visibility for Jackson, this does not work with external classes. So how can I set visibility of a class without using @JsonAutoDetect annotation and also not to change the global configuration?

虽然使用@JsonAutoDetect注释可以自定义类对Jackson的可见性,但这不适用于外部类。那么如何在不使用@JsonAutoDetect注释的情况下设置类的可见性,而不是更改全局配置?

1 个解决方案

#1


1  

You should be able to use jacksons MixIn feature. With this approach you can control all the configuration of a class by another class definition of your choice.

您应该能够使用jacksons MixIn功能。使用此方法,您可以通过您选择的另一个类定义来控制类的所有配置。

https://github.com/FasterXML/jackson-docs/wiki/JacksonMixInAnnotations

You can also check out one of my github projects to see the use of that feature:

您还可以查看我的一个github项目,看看该功能的用途:

https://github.com/Antibrumm/jackson-antpathfilter

#1


1  

You should be able to use jacksons MixIn feature. With this approach you can control all the configuration of a class by another class definition of your choice.

您应该能够使用jacksons MixIn功能。使用此方法,您可以通过您选择的另一个类定义来控制类的所有配置。

https://github.com/FasterXML/jackson-docs/wiki/JacksonMixInAnnotations

You can also check out one of my github projects to see the use of that feature:

您还可以查看我的一个github项目,看看该功能的用途:

https://github.com/Antibrumm/jackson-antpathfilter