使用自定义 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>