Skip to content

Instantly share code, notes, and snippets.

@kawasima
Created March 26, 2021 07:28
Show Gist options
  • Save kawasima/6dcb2ea08d471cb4188552dd520cec9e to your computer and use it in GitHub Desktop.
Save kawasima/6dcb2ea08d471cb4188552dd520cec9e to your computer and use it in GitHub Desktop.
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