jackson 如何仅序列化使用自定义注解进行注解的属性

r8xiu3jd  于 2022-11-08  发布在  其他
关注(0)|答案(1)|浏览(245)

我们在整个应用程序中使用Jackson来将Java对象序列化和反序列化为JSON,效果非常好。
是否可能(也许通过自定义序列化程序)只序列化使用自定义注解注解的Java对象的属性?
因此,给定自定义注解:

public @interface SpecialField {}

和下面的bean

public SomeBean {
   @SpecialField
   private Object propertyIncluded;

   private Object propertyExcluded;
}

自定义序列化器(或某种等效机制)序列化propertyIncluded(使用常规的Jackson对象Map器)并忽略propertyExcluded会是什么样子?
在这个用例中,我们不能使用标准的Jackson注解(@JsonIgnore),因为它会破坏应用程序中的其他序列化用例。

6tdlim6h

6tdlim6h1#

虽然这可能不是你想要的,但是通过一些调整,可以使Jackson引擎以不同的方式序列化对象。在下面的例子中,我创建了两种类型的序列化器,它们将或不将标记为transient的字段序列化。

import java.io.Serializable;

import org.codehaus.jackson.annotate.JsonAutoDetect;
import org.codehaus.jackson.map.ObjectMapper;

public class Test {

    public static void main(String[] args) throws Exception {
        ISerializer d = new Doesnt();
        ISerializer o = new Observes();

        SomeObject obj = new SomeObject();

        System.out.println("Doesnt: " + d.serialize(obj));

        System.out.println("Observes: " + o.serialize(obj));
    }
    public static class Doesnt implements ISerializer<SomeObject> {

        @Override
        public String serialize(SomeObject o) throws Exception {
            ObjectMapper om = new ObjectMapper();
            om.setVisibilityChecker(
                    om.getSerializationConfig().
                    getDefaultVisibilityChecker().
                    withFieldVisibility(JsonAutoDetect.Visibility.ANY).
                    withGetterVisibility(JsonAutoDetect.Visibility.ANY));
            return om.writeValueAsString(o);
        }

    }

    public static class Observes implements ISerializer<SomeObject> {

        @Override
        public String serialize(SomeObject o) throws Exception {
            ObjectMapper om = new ObjectMapper();
            om.setVisibilityChecker(
                    om.getSerializationConfig().
                    getDefaultVisibilityChecker().
                    withFieldVisibility(JsonAutoDetect.Visibility.ANY).
                    withGetterVisibility(JsonAutoDetect.Visibility.NONE));
            return om.writeValueAsString(o);
        }       
    }
    public interface ISerializer<T> {
        public String serialize(T o) throws Exception;
    }

    public static class SomeObject implements Serializable {
        private static final long serialVersionUID = 745063791749142843L;
        private transient String myVar = "Transient";
        private String myOther = "Not Transient";
        public String getMyVar() {
            return myVar;
        }
        public void setMyVar(String myVar) {
            this.myVar = myVar;
        }
        public String getMyOther() {
            return myOther;
        }
        public void setMyOther(String myOther) {
            this.myOther = myOther;
        }
    }
}

输出:

Doesnt: {"myVar":"Transient","myOther":"Not Transient"}
Observes: {"myOther":"Not Transient"}

我认为更改序列化程序以扩展JsonSerializer类并在其中执行类似的操作是相当容易的。

相关问题