如何仅序列化使用自定义注释注释的属性

时间:2014-10-02 22:51:36

标签: java json jackson

我们在整个应用程序中使用jackson将Java对象序列化和反序列化为JSON。它很棒。

是否可以通过自定义序列化程序仅序列化使用自定义注释注释的Java对象的属性?

因此,给定自定义注释:

public @interface SpecialField {}

以下豆子

public SomeBean {
   @SpecialField
   private Object propertyIncluded;

   private Object propertyExcluded;
}

自定义序列化程序(或某些等效机制)是什么样的序列化propertyIncluded(使用普通的jackson对象映射器)并忽略propertyExcluded?

我们不能在这个用例中使用标准的jackson注释(@JsonIgnore),因为它会破坏我们应用程序中的其他序列化用例。

1 个答案:

答案 0 :(得分:0)

虽然这可能不是您想要的,但可以通过一些调整使杰克逊引擎以不同方式序列化对象。在下面的示例中,我创建了两种类型的序列化程序,它们将序列化标记为瞬态的字段。

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类并在其中执行类似的操作会相当容易。