您可以使用 annotation JsonTypeInfo
,它准确地告诉 Jackson 并且您不需要编写自定义序列化程序。有多种方法可以包含此信息,但对于您的特定问题,您将使用As.WRAPPER_OBJECT
和Id.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"}}}