Jackson ObjectMapper默认将枚举类型Enum转换为它的名称,亦即为字符串,比如将枚举SUCCESS(“SUCCESS”, 200)输出为“SUCCESS”,这丢失了很多额外的信息,并且前端也不易处理,如将服务器返回状态定义为枚举:
public enum ActionStatus { SUCCESS("SUCCESS", 200), FAIL_500("FAIL", 500); private final String status; private final int code; private ActionStatus(String status, int code) { this.status = status; this.code = code; } public String getStatus() { return status; } public int getCode() { return code; }}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
经测试,无论是JsonProperty还是JsonGetter都不能解决此问题,输出依旧为枚举的名称,而在枚举中,默认的toString方法是不能覆盖的,想来想去,只好手动进行处理:
1. 在ActionStatus添加转换为Map的方法;
2. 实现JsonSerializer接口,注册类型序列化方法
具体实现如下:
// 将此方法添加在ActionStatus中public Map<String, Object> toMap() { return ImmutableMap.<String, Object>builder() .put("status", status) .put("code", code) .build();}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
实现序列化接口:
public class ActionStatusSerializer extends JsonSerializer<ActionStatus> { /* (non-Javadoc) * @see com.fasterxml.jackson.databind.JsonSerializer#serialize(java.lang.Object, com.fasterxml.jackson.core.JsonGenerator, com.fasterxml.jackson.databind.SerializerProvider) */ @Override public void serialize(ActionStatus value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { Optional<ActionStatus> data = Optional.of(value); if (data.isPresent()) { jgen.writeObject(data.get().toMap()); } else { jgen.writeString(""); } }}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
最后注册到ObjectMapper的serializersByType属性,即可实现JSON对象输出,如下:
{"status":"SUCCESS","code":200}
- 1
结论
Jackson提供的注解能解决大部分的问题,但有时也需要进行手动解决,这是JsonSerializer、JsonDeserializer就是一种非常优秀的选择。