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

问题描述

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

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 序列化为类似 data.getClass.getName() 的内容,而不是总是有一个名为 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.

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 作为包装器对象,因为它仅用作 placeholder.如果要删除它,则必须为整个 类编写自定义序列化程序,即JsonSerializer.

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>.

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

09-02 10:29