问题
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" }
回答1:
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.
来源:https://stackoverflow.com/questions/43978724/jackson-json-de-serialization-with-views