0

Im trying to serialize a property based on the view. Unfortunately the code below doesn't work as Jackson reports a conflicting getter propperty "userId". Is there any way to get an object according to the view in an specific representation?

  @JsonView(Views.Mongo.class)
  @JsonProperty("userId")
  public ObjectId getUserId() {
        return userId;
  }

  @JsonView(Views.Frontend.class)
  @JsonProperty("userId")
  public String getUserIdAsString() {
      return userId.toString();
  }

This is what I want:

View 1:

{ userId: { '$oid' : "16418256815618" } }

View 2:

{ userId: "16418256815618" }
Thomas
  • 97
  • 1
  • 1
  • 7

1 Answers1

0

I think you can write a custom serializer which does this task based on the active view as shown below.

    public class ObjectIdSerializer extends JsonSerializer<ObjectId> {

    @Override
    public void serialize(ObjectId objectId, JsonGenerator gen, SerializerProvider provider) throws IOException {
        if (provider.getActiveView() == Frontend.class) {
            gen.writeString(objectId.toString());
        } else {
            // Do default serialization of ObjectId. 
            gen.writeStartObject();
            gen.writeFieldName("idField1");
            gen.writeString(objectId.getIdField1());
            gen.writeFieldName("idField2");
            gen.writeString(objectId.getIdField2());
            gen.writeEndObject();
        }
    }
}

Then modify your pojo as shown below

@JsonSerialize(using=ObjectIdSerializer.class)
public ObjectId getUserId() {
    return userId;
}

You don't have to pass any view annotation on your getter/field as it is taken care in custom serializer.

In this example I have done default serialization manually. Alternatively, you can accomplish it using the default serializer by registering a serializer modifier as explained in the question How to access default jackson serialization in a custom serializer.

Community
  • 1
  • 1
Justin Jose
  • 2,121
  • 1
  • 16
  • 15