1
2
3
4
5 package gboat2.base.bridge.util.json;
6
7 import java.io.IOException;
8 import java.util.HashMap;
9 import java.util.Map;
10
11 import org.apache.commons.beanutils.BeanUtils;
12 import org.slf4j.Logger;
13 import org.slf4j.LoggerFactory;
14
15 import com.fasterxml.jackson.core.JsonGenerator;
16 import com.fasterxml.jackson.core.JsonProcessingException;
17 import com.fasterxml.jackson.databind.JsonSerializer;
18 import com.fasterxml.jackson.databind.SerializerProvider;
19
20
21
22
23
24
25
26
27 @SuppressWarnings({ "rawtypes", "unchecked" })
28 public class GboatEnumSerializer extends JsonSerializer<Enum> {
29
30 private static final Logger logger = LoggerFactory.getLogger(GboatEnumSerializer.class);
31
32 @Override
33 public void serialize(Enum value, JsonGenerator jgen, SerializerProvider provider)
34 throws IOException, JsonProcessingException {
35 Map<String, Object> props = null;
36 try {
37 props = BeanUtils.describe(value);
38 props.remove("class");
39 props.remove("declaringClass");
40 } catch (Exception e) {
41 logger.warn("将枚举类 [" + value.getClass() + "] 使用 jackson 序列化成 JSON 字符串发生错误!", e);
42 props = new HashMap<String, Object>();
43 }
44 props.put("name", value.name());
45 jgen.writeObject(props);
46 }
47 }