Skip to content

Instantly share code, notes, and snippets.

@ningthoujam-lokhendro
Last active June 11, 2023 15:08
Show Gist options
  • Save ningthoujam-lokhendro/fbc0ca3cf51333a230b4 to your computer and use it in GitHub Desktop.
Save ningthoujam-lokhendro/fbc0ca3cf51333a230b4 to your computer and use it in GitHub Desktop.
POJO to Map conversion
/**
* Using Apache Common Bean Utils.
*/
import org.apache.commons.beanutils.BeanUtils;
import java.util.HashMap;
public class ApacheCommonExample throws IllegalAccessException,
InvocationTargetException, NoSuchMethodException {
public HashMap<String,Object> convert(Person person) {
HashMap<String,Object> hashMap = BeanUtils.describe(person);
return hashMap;
}
}
/**
* Using Introspector.
*/
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
public class IntrospectorExample {
public HashMap<String, Object> convert(Person person)
throws IntrospectionException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
HashMap<String, Object> hashMap = new HashMap<String, Object>();
BeanInfo beanInfo = Introspector.getBeanInfo(device.getClass());
for(PropertyDescriptor pd : beanInfo.getPropertyDescriptors()) {
Method reader = pd.getReadMethod();
if(reader != null) {
hashMap.put(pd.getName(), reader.invoke(device));
}
}
return hashMap;
}
public void mergeObject(Person source, Person target)
throws IntrospectionException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
BeanInfo beanInfo;
beanInfo = Introspector.getBeanInfo(target.getClass());
// iterate all attributes
for (PropertyDescriptor descriptor : beanInfo.getPropertyDescriptors()) {
// only copy writable attributes
if (descriptor.getWriteMethod() != null) {
//Object oriVal = descriptor.getReadMethod().invoke(target);
// only copy values where destination value is null
//if (oriVal == null) {
Object defaultValue = descriptor.getReadMethod().invoke(source);
if(defaultValue != null)
descriptor.getWriteMethod().invoke(target,defaultValue);
//}
}
}
}
}
/**
* Using Jackson Databind.
*/
import java.util.HashMap;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonExample {
private static final ObjectMapper objectMapper = new ObjectMapper();
@SuppressWarnings("unchecked")
public HashMap<String, Object> convert(Person person) {
HashMap<String, Object> hashMap = objectMapper.convertValue(person, HashMap.class);
return hashMap;
}
}
// A POJO getter/setter
class Person{
String name;
String age;
//getter and setter
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment