package xxxxxxxxxxxxx;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@Slf4j
@Configuration
public class JacksonConfig {
@Bean
public ObjectMapper objectMapper() {
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(Enum.class, new GenericEnumSerializer());
mapper.registerModule(module);
return mapper;
}
public static class GenericEnumSerializer extends JsonSerializer<Enum> {
private static final Map<Class<? extends Enum<?>>, Field> enumFieldCache = new ConcurrentHashMap<>();
@Override
public void serialize(Enum anEnum, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeStartObject();
Class<?> enumClass = anEnum.getClass();
try {
jsonGenerator.writeStringField("key", anEnum.name());
Field nameField = enumFieldCache.computeIfAbsent((Class<? extends Enum<?>>) enumClass, cls -> {
try {
Field field = cls.getDeclaredField("name");
field.setAccessible(true);
return field;
} catch (NoSuchFieldException e) {
log.warn("no 'name' field in enum class: {}", cls.getName());
return null;
}
});
if (nameField != null) {
String val = nameField.get(anEnum).toString();
jsonGenerator.writeStringField("value", val);
}
} catch (IllegalAccessException e) {
log.warn("Cannot access 'name' field in enum class: {}", enumClass.getName());
}
jsonGenerator.writeEndObject();
}
}
}
{
"name": "test",
"test": {
"key": "dev",
"value": "开发"
},
"a": {
"key": "A",
"value": "A1"
},
"b": {
"key": "X",
"value": "X1"
}
}
标签:jackson,Springboot,自定义,jsonGenerator,field,import,序列化,com,name From: https://www.cnblogs.com/namedlxd/p/18408133