Jackson JSON反序列化视图

Jackson JSON反序列化视图

问题描述:

我试图根据视图序列化属性。不幸的是,下面的代码不起作用,因为Jackson报告了一个冲突的getter属性userId。有没有办法根据特定表示中的视图获取对象?

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();
  }

这就是我想要的:

查看1:

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

查看2:

{ userId: "16418256815618" }


我认为您可以编写一个自定义序列化程序,它根据活动视图执行此任务,如下所示。

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();
        }
    }
}

然后如图所示修改你的pojo下面

Then modify your pojo as shown below

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

您不必在getter / field上传递任何视图注释在自定义序列化程序中使用它。

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

在此示例中,我手动完成了默认序列化。或者,您可以使用默认序列化程序通过注册序列化程序修饰符来完成它,如问题如何在自定义序列化程序中访问默认的jackson序列化

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.