杰克逊动态属性名称 [英] Jackson dynamic property names

查看:124
本文介绍了杰克逊动态属性名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想序列化一个对象,以便根据字段的类型对其中一个字段进行不同的命名。例如:

I would like serialize an object such that one of the fields will be named differently based on the type of the field. For example:

public class Response {
    private Status status;
    private String error;
    private Object data;
        [ getters, setters ]
    }

在这里,我想要这个领域数据要序列化为类似 data.getClass.getName()而不是总是有一个名为<$ c的字段$ c> data 根据情况包含不同的类型。

Here, I would like the field data to be serialized to something like data.getClass.getName() instead of always having a field called data which contains a different type depending on the situation.

我如何使用Jackson实现这样的技巧?

How might I achieve such a trick using Jackson?

推荐答案

使用自定义 JsonSerializer

Using a custom JsonSerializer.

public class Response {
  private String status;
  private String error;

  @JsonProperty("p")
  @JsonSerialize(using = CustomSerializer.class)
  private Object data;

  // ...
}

public class CustomSerializer extends JsonSerializer<Object> {
  public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
    jgen.writeStartObject();
    jgen.writeObjectField(value.getClass().getName(), value);
    jgen.writeEndObject();
  }
}

然后,假设您要序列化以下两个对象:

And then, suppose you want to serialize the following two objects:

public static void main(String... args) throws Exception {
  ObjectMapper mapper = new ObjectMapper();
  Response r1 = new Response("Error", "Some error", 20);
  System.out.println(mapper.writeValueAsString(r1));
  Response r2 = new Response("Error", "Some error", "some string");
  System.out.println(mapper.writeValueAsString(r2));
}

第一个将打印:

{"status":"Error","error":"Some error","p":{"java.lang.Integer":20}}

第二个:

{"status":"Error","error":"Some error","p":{"java.lang.String":"some string"}}

我使用了名称 p 作为包装器对象,因为它只会提供服务作为 p laceholder。如果要删除它,则必须为整个类编写自定义序列化程序,即 JsonSerializer< Response>

I have used the name p for the wrapper object since it will merely serve as a placeholder. If you want to remove it, you'd have to write a custom serializer for the entire class, i.e., a JsonSerializer<Response>.

这篇关于杰克逊动态属性名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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