Created
March 26, 2021 07:28
-
-
Save kawasima/6dcb2ea08d471cb4188552dd520cec9e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.fasterxml.jackson.databind.BeanDescription; | |
import com.fasterxml.jackson.databind.JavaType; | |
import com.fasterxml.jackson.databind.ObjectMapper; | |
import com.fasterxml.jackson.databind.SerializationConfig; | |
import com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition; | |
import com.fasterxml.jackson.databind.introspect.ClassIntrospector; | |
import java.util.LinkedHashMap; | |
import java.util.Map; | |
public class PojoToMap { | |
private final ObjectMapper mapper = new ObjectMapper(); | |
public <T> Map<String, Object> pojoToMap(T pojo) { | |
SerializationConfig serializationConfig = mapper.getSerializationConfig(); | |
ClassIntrospector classIntrospector = serializationConfig.getClassIntrospector(); | |
JavaType javaType = serializationConfig.getTypeFactory().constructType(pojo.getClass()); | |
BeanDescription beanDescription = classIntrospector.forSerialization(serializationConfig, javaType, serializationConfig); | |
Map<String, Object> map = new LinkedHashMap<>(); | |
for (BeanPropertyDefinition propDef : beanDescription.findProperties()) { | |
map.put(propDef.getName(), propDef.getAccessor().getValue(pojo)); | |
} | |
return map; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment