Serialize one class in two different ways with Jackson

后端 未结 2 1820
滥情空心
滥情空心 2020-12-18 01:25

In one of our projects we use a java webapp talking to a MongoDB instance. In the database, we use DBRefs to keep track of some object relations. We (de)seriali

2条回答
  •  囚心锁ツ
    2020-12-18 02:12

    Use a custom JSONSerializer and apply your logic in the serialize method:

    public static class FooReference {
        public DBRef foo;
    
        @JsonSerialize(using = CustomSerializer.class)
        public Foo getFoo() {
            return foo.fetch();
        }
    }
    
    public class CustomSerializer extends JsonSerializer {
       public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider)
           throws IOException, JsonProcessingException {
         // jgen.writeObjectField ...
       }
    }
    
        

    提交回复
    热议问题