1.背景
- 項(xiàng)目中后端要把枚舉類型傳給前端部凑,但是前端要用枚舉的code和desc分歇,且這兩個(gè)字段要跟主類平行結(jié)構(gòu)善炫。我這么說大家可能不太理解,下面上代碼
實(shí)體類
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private long id;
private TaskStatus taskStatus;
}
枚舉類
@Getter
@AllArgsConstructor
public enum TaskStatus implements IEnum<String> {
/**
* 任務(wù)狀態(tài)
*/
UNPUBLISHED("unpublished", "待發(fā)布"),
PUBLISHED("published", "發(fā)布"),
PROCESSING("processing", "進(jìn)行中"),
AHEAD_COMPLETED("ahead_completed", "提前完成"),
COMPLETED("completed", "已完成"),
OVERDUE("overdue", "已超期"),
;
/**
* 成員變量
*/
private final String code;
private final String desc;
public static TaskStatus getByCode(String code) {
for (TaskStatus status : TaskStatus.values()) {
if (status.code.equals(code)) {
return status;
}
}
return null;
}
public static TaskStatus getByDesc(String desc) {
for (TaskStatus status : TaskStatus.values()) {
if (status.desc.equals(desc)) {
return status;
}
}
return null;
}
}
枚舉接口類
public interface IEnum<T> {
T getCode();
T getDesc();
}
- 起初用的fastjson岂丘,但是fastjson不支持細(xì)粒度控制陵究,所以換jackson,jackson可以更細(xì)粒度的控制bean的序列化。
- 我的思路是通過IEnum接口來識(shí)別需要自定義序列化的枚舉變量奥帘,然后調(diào)用自定義序列化方法進(jìn)行序列化數(shù)據(jù)。
照著網(wǎng)上的例子編寫了如下自定義序列化實(shí)現(xiàn)
public class EnumsCodec extends JsonSerializer {
@Override
public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
String className = o.getClass().getSimpleName();
char[] cs = className.toCharArray();
cs[0] = toLowerCase(cs[0]);
className = String.valueOf(cs);
jsonGenerator.writeStringField(className, o.toString());
jsonGenerator.writeStringField(className + "Desc", ((IEnum<String>) o).getDesc());
}
public char toUpperCase(char chars) {
if (97 <= chars && chars <= 122) {
chars -= 32;
}
return chars;
}
public char toLowerCase(char chars) {
if (65 <= chars && chars <= 90) {
chars += 32;
}
return chars;
}
}
JsonUtil類如下
@Slf4j
public class JsonUtil {
private static final ObjectMapper mapper = new ObjectMapper();
static {
mapper.findAndRegisterModules();
SimpleModule simpleModule = new SimpleModule();
//注冊(cè)一個(gè)統(tǒng)一的枚舉序列方法仪召,實(shí)現(xiàn)IEnum接口的枚舉序列化時(shí)取desc字段
simpleModule.addSerializer(IEnum.class, new EnumsCodec());
mapper.registerModule(simpleModule);
}
private JsonUtil() {
}
/**
* json serialization.
*
* @param obj 要進(jìn)行序列化的對(duì)象
* @return 返回序列化之后的字符串
*/
public static String dumps(Object obj) {
try {
String result = mapper.writeValueAsString(obj);
return result;
} catch (JsonProcessingException ex) {
log.error("failed serialize object to json string: {}", ex);
}
return null;
}
/**
* json deserialization.
*
* @param jsonStr 序列化字符串
* @param cls 指定反序列化之后的類信息
* @return 返回反序列化之后的實(shí)例對(duì)象
*/
public static <T> T loads(String jsonStr, Class<T> cls) {
T object = null;
try {
object = mapper.readValue(jsonStr, cls);
} catch (IOException ex) {
log.error("failed deserialize string: {} to Class {}'s instance, error: {}", jsonStr,
cls.getName(), ex);
}
return object;
}
/**
* json deserialization.
*
* @param jsonStr 序列化字符串
* @param valueTypeRef 指定反序列化之后的類信息
* @return 返回反序列化之后的實(shí)例對(duì)象
*/
public static <T> T loads(String jsonStr, TypeReference valueTypeRef) {
T object = null;
try {
object = mapper.readValue(jsonStr, valueTypeRef);
} catch (IOException ex) {
log.error("failed deserialize string: {} to Class {}'s instance, error: {}", jsonStr,
valueTypeRef.getClass().getName(), ex);
}
return object;
}
public static <T> T loads(InputStream inputStream, Class<T> cls) {
T obj = null;
try {
obj = mapper.readValue(inputStream, cls);
} catch (JsonParseException e) {
log.error("JsonUtil:jjson轉(zhuǎn)換異常寨蹋!", e);
} catch (JsonMappingException e) {
log.error("JsonUtil:json映射異常", e);
} catch (IOException e) {
log.error("JsonUtil:json轉(zhuǎn)換異常", e);
}
return obj;
}
public static JsonNode jsonNode(String jsonStr) {
try {
return mapper.readTree(jsonStr);
} catch (IOException ex) {
log.error("failed deserialize string: {} to JsonNode, error: {}", jsonStr, ex);
}
return null;
}
public static void main(String[] args) throws IOException {
User user = new User();
user.setId(1);
user.setTaskStatus(TaskStatus.COMPLETED);
String str = mapper.writeValueAsString(user);
System.out.println(str);
String str1 = "{\"id\":1,\"taskStatus\":\"COMPLETED\"}";
User user1 = mapper.readValue(str1, User.class);
System.out.println(user1.getTaskStatus());
}
}
運(yùn)行后報(bào)錯(cuò)如下:
Exception in thread "main" com.fasterxml.jackson.core.JsonGenerationException: Can not write a field name, expecting a value
at com.fasterxml.jackson.core.JsonGenerator._reportError(JsonGenerator.java:1676)
at com.fasterxml.jackson.core.json.WriterBasedJsonGenerator.writeFieldName(WriterBasedJsonGenerator.java:109)
at com.fasterxml.jackson.core.json.JsonGeneratorImpl.writeStringField(JsonGeneratorImpl.java:202)
at com.***.jsoncodec.EnumsCodec.serialize(EnumsCodec.java:25)
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:672)
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:678)
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:157)
at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:130)
at com.fasterxml.jackson.databind.ObjectMapper._configAndWriteValue(ObjectMapper.java:3631)
at com.fasterxml.jackson.databind.ObjectMapper.writeValueAsString(ObjectMapper.java:2998)
at com.***.util.JsonUtil.main(JsonUtil.java:119)
百思不得解,經(jīng)過各種實(shí)驗(yàn)扔茅,發(fā)現(xiàn)在2.3版本可以已旧,2.7版本不行,但是我們項(xiàng)目強(qiáng)依賴2.7版本召娜,這怎么辦呢运褪。。玖瘸。秸讹。。雅倒。
google了一遍璃诀,照著網(wǎng)上的方法把修改如下
@Override
public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
String className = o.getClass().getSimpleName();
char[] cs = className.toCharArray();
cs[0] = toLowerCase(cs[0]);
className = String.valueOf(cs);
jsonGenerator.writeStartObject();
jsonGenerator.writeStringField(className, o.toString());
jsonGenerator.writeStringField(className + "Desc", ((IEnum<String>) o).getDesc());
jsonGenerator.writeEndObject();
}
運(yùn)行結(jié)果如下
{"id":1,"taskStatus":{"taskStatus":"COMPLETED","taskStatusDesc":"已完成"}}
這個(gè)結(jié)果不是我想要的呀。
無比愁暢蔑匣。劣欢。。裁良。凿将。。
折騰了一天价脾,還是沒找辦法牧抵,我已經(jīng)放棄。找前端說搞不出來彼棍。
這個(gè)時(shí)候灭忠,群里的一位大神的一句話提醒了我膳算,他說Can not write a field name, expecting a value這個(gè)報(bào)錯(cuò)可能是新版本做了完整性檢查了,于是跟了一下源碼弛作,發(fā)現(xiàn)2.7版本在序列化時(shí)候涕蜂,key是固定好的,不能直接寫入field映琳。那我是不是先給他寫一個(gè)值机隙,然后再寫入一個(gè)field的就可以了呢?于是動(dòng)手試了一下萨西,改造如下
@Override
public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
String className = o.getClass().getSimpleName();
char[] cs = className.toCharArray();
cs[0] = toLowerCase(cs[0]);
className = String.valueOf(cs);
jsonGenerator.writeString(o.toString());
jsonGenerator.writeStringField(className + "Desc", ((IEnum<String>) o).getDesc());
}
運(yùn)行結(jié)果如下
{"id":1,"taskStatus":"COMPLETED","taskStatusDesc":"已完成"}
完美有鹿,問題到此解決了。
所以說谎脯,有時(shí)候你跟真相只差一步之遙葱跋,就缺大神指點(diǎn)。