Serialize one class in two different ways using Jackson

In one of our projects, we use java webapp talking to an instance of MongoDB. In the database we use DBRefsto track some object relationships. We (de) serialize with POJO objects using jackson (using mongodb-jackson-mapper).

However, we use the same POJOs to then (de) serialize to the outside world, where our front is dealing with JSON representation.

Now we need a way to serialize to the outside world to contain the reference object from DBRef(so that the user interface can represent the complete object), while we obviously want DBRefthe database, not the entire object.

Now I have written unverified static nested class code:

public static class FooReference {
    public DBRef<Foo> foo;

    // FIXME how to ensure that this doesn't go into the database?
    public Foo getFoo() {
        return foo.fetch();
    }
}

, , , () getFoo(), , , - . ? ?

+5
2

, , , View ObjectMapper, . , :

public static class FooReference {
    public DBRef<Foo> foo;

    @JsonView(Views.WebView.class)
    public Foo getFoo() {
        return foo.fetch();
    }
}

:

class Views {
    static class WebView { }
}

:

SerializationConfig conf = objectMapper.getSerializationConfig().withView(Views.WebView.class);
objectMapper.setSerializationConfig(conf);

. , MongoDB , . JsonView , , :

objectMapper.configure(SerializationConfig.Feature.DEFAULT_VIEW_INCLUSION, false);

Wiki Jackson.

: Jackson MixIns, () , Jackson 2.0 ( ) .

+8

JSONSerializer serialize:

public static class FooReference {
    public DBRef<Foo> foo;

    @JsonSerialize(using = CustomSerializer.class)
    public Foo getFoo() {
        return foo.fetch();
    }
}

public class CustomSerializer extends JsonSerializer<Object> {
   public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider)
       throws IOException, JsonProcessingException {
     // jgen.writeObjectField ...
   }
}
+2

All Articles