How do I serialize an associated object differently using Jackson and annotations?

前端 未结 3 1870
无人及你
无人及你 2021-02-04 13:42

Given the following class hierarchy, I would like Foo to be serialized differently depending on the context it is used in my class hierarchy.

public class Foo {
         


        
3条回答
  •  礼貌的吻别
    2021-02-04 14:10

    I would use the google code gson
    documentation in here https://code.google.com/p/google-gson/
    Maven dependency is:

    
                com.google.code.gson
                gson
                2.2.1
            
    

    The annotations are like this:
    To expose the field user the @Expose annotation
    To generate a special name for the field in the parsed json user the @SerializedName("fieldNameInJSON") annotation
    So your classes would look like this:

        public class Foo {
    @SerializedName("bar")
        @Expose
            public String bar;
    @SerializedName("biz")
        @Expose
            public String biz;
        }
    
        public class FooContainer {
    @SerializedName("fooA")
        @Expose
            public Foo fooA;
    @SerializedName("fooB")
        @Expose
            public Foo fooB;
        }
    

    To serialize to JSON you will use a code that looks like this:

    public String convertToJSON(FooContainer fc) {
            if (fc != null) {
                GsonBuilder gson = new GsonBuilder();
                return gson.excludeFieldsWithoutExposeAnnotation().create().toJson(fc);
            }
            return "";
        }
    

    It would look the same for Lists for example:

    public String convertToJSON(List fcs) {
                if (fcs != null) {
                    GsonBuilder gson = new GsonBuilder();
                    return gson.excludeFieldsWithoutExposeAnnotation().create().toJson(fcs);
                }
                return "";
            }
    

提交回复
热议问题