33

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

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

在这里,我希望将字段data序列化为类似的东西,data.getClass.getName()而不是总是有一个名为的字段,该字段data根据情况包含不同的类型。

我怎样才能使用杰克逊实现这样的技巧?

4

4 回答 4

39

我有一个使用@JsonAnyGetter注释的更简单的解决方案,它就像一个魅力。

import java.util.Collections;
import java.util.Map;

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

    @JsonIgnore
    private Object data;

    [getters, setters]

    @JsonAnyGetter
    public Map<String, Object> any() {
        //add the custom name here
        //use full HashMap if you need more than one property
        return Collections.singletonMap(data.getClass().getName(), data);
    }
}

不需要包装器,不需要自定义序列化程序。

于 2017-12-18T09:28:50.773 回答
38

使用自定义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();
  }
}

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

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花边夹。如果要删除它,则必须为整个类编写一个自定义序列化程序,即JsonSerializer<Response>.

于 2012-08-26T23:10:20.203 回答
5

我自己的解决方案。

@Data
@EqualsAndHashCode
@ToString
@JsonSerialize(using = ElementsListBean.CustomSerializer.class)
public class ElementsListBean<T> {

    public ElementsListBean()
    {
    }

    public ElementsListBean(final String fieldName, final List<T> elements)
    {
        this.fieldName = fieldName;
        this.elements = elements;
    }

    private String fieldName;

    private List<T> elements;

    public int length()
    {
        return (this.elements != null) ? this.elements.size() : 0;
    }

    private static class CustomSerializer extends JsonSerializer<Object> {
        public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException,
                JsonProcessingException
        {
            if (value instanceof ElementsListBean) {
                final ElementsListBean<?> o = (ElementsListBean<?>) value;
                jgen.writeStartObject();
                jgen.writeArrayFieldStart(o.getFieldName());
                for (Object e : o.getElements()) {
                    jgen.writeObject(e);
                }
                jgen.writeEndArray();
                jgen.writeNumberField("length", o.length());
                jgen.writeEndObject();
            }
        }
    }
}
于 2012-09-06T12:32:05.687 回答
4

您可以使用 annotation JsonTypeInfo,它准确地告诉 Jackson 并且您不需要编写自定义序列化程序。有多种方法可以包含此信息,但对于您的特定问题,您将使用As.WRAPPER_OBJECTId.CLASS。例如:

public static class Response {
    private Status status;
    private String error;
    @JsonTypeInfo(include = As.WRAPPER_OBJECT, use = Id.CLASS)
    private Object data;
}

但是,这不适用于原始类型,例如字符串或整数。无论如何,对于原语,您都不需要这些信息,因为它们本身就以 JSON 表示,而 Jackson 知道如何处理它们。使用注释的额外好处是,如果您需要,您可以免费获得反序列化。这是一个例子:

public static void main(String[] args) throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    Response r1 = new Response("Status", "An error", "some data");
    Response r2 = new Response("Status", "An error", 10);
    Response r3 = new Response("Status", "An error", new MyClass("data"));
    System.out.println(mapper.writeValueAsString(r1));
    System.out.println(mapper.writeValueAsString(r2));
    System.out.println(mapper.writeValueAsString(r3));
}

@JsonAutoDetect(fieldVisibility=Visibility.ANY)
public static class MyClass{
    private String data;
    public MyClass(String data) {
        this.data = data;
    }
}

结果:

{"status":"Status","error":"An error","data":"some data"}
{"status":"Status","error":"An error","data":10}
{"status":"Status","error":"An error","data":{"some.package.MyClass":{"data":"data"}}}
于 2012-08-27T16:36:26.730 回答