Serialize @JsonIgnore-d field

后端 未结 1 533
暖寄归人
暖寄归人 2020-12-10 15:29

I have class with @JsonIgnore-d field:

public class MyClass {
    ...
    @JsonIgnore
    private SomeType myfield;
    ...
    // getters &         


        
相关标签:
1条回答
  • 2020-12-10 16:12

    It is possible to configure ObjectMapper to disable a JsonIgnore function. Following are some possible solution you can try with:

    1. Disable JsonIgnore function for a particular annotated field.

    You can create a custom JsonIgnore annotation and a custom JacksonAnnotationIntrospector to remove the annotation from mapper context. Following are the ideas:

    Annotate @MyJsonIgnore to the fields that should be ignored while serialization:

    @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
    public class MyClass {
    
        @MyJsonIgnore
        private SomeType myField;
    
    }
    

    @MyJsonIgnore is a simple custom annotation that wrap @JsonIgnore:

    @Retention(RetentionPolicy.RUNTIME)
    @JacksonAnnotationsInside
    @JsonIgnore
    public @interface MyJsonIgnore {
    }
    

    A custom JacksonAnnotationIntrospector is implemented to remove @MyJsonIgnore from mapper context:

    public class DisablingMyJsonIgnoreIntrospector extends JacksonAnnotationIntrospector {
    
    @Override
    public boolean isAnnotationBundle(final Annotation ann) {
        if (ann.annotationType().equals(MyJsonIgnore.class)) {
            return false;
        } else {
            return super.isAnnotationBundle(ann);
        }
    }
    

    After that, you can set the introspector on a ObjectMapper during configuration:

    ObjectMapper mapper = new ObjectMapper();
    mapper.setAnnotationIntrospector(new DisablingMyJsonIgnoreIntrospector());
    

    It results that the fields annotated with @MyJsonIgnore can be marshaled properly.

    2. Disable JsonIgnore function for the mapper

    Your can create a custom JacksonAnnotationIntrospector and override hasIgnoreMarker method to always return false:

    public static class DisablingJsonIgnoreIntrospector extends JacksonAnnotationIntrospector {
    
        @Override
        public boolean hasIgnoreMarker(final AnnotatedMember m) {
            return false;
        }
    
    }
    

    hasIgnoreMarker is to check whether there is annotation to ignore json property. Return false will disable the JsonIngore function.

    3. Disable all annotations and specify what kinds of properties are auto-detected for a given ObjectMapper:

    final ObjectMapper mapper = new ObjectMapper();
    mapper.disable(MapperFeature.USE_ANNOTATIONS);
    mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
    

    This simply disable all annotations.

    Hope this can help.

    0 讨论(0)
提交回复
热议问题