Jackson JSON反序列化视图 [英] Jackson JSON de-serialization with views

查看:144
本文介绍了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.

这篇关于Jackson JSON反序列化视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆