Skip to content

Instantly share code, notes, and snippets.

@jcyuyi
Last active March 20, 2019 05:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jcyuyi/f982a8187d5210def4854444c460a5e3 to your computer and use it in GitHub Desktop.
Save jcyuyi/f982a8187d5210def4854444c460a5e3 to your computer and use it in GitHub Desktop.
JacksonMapUtils.java
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import org.springframework.util.ReflectionUtils;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
public class JacksonMapUtils {
/**
* Get map of a flat xml java bean using JacksonXmlProperty annotations
* <p> Notice: Null values will be ignored </p>
*/
public static <T> Map<String, String> getMapOfFlatXmlBean(Class<T> clz, T obj) {
Map<String, String> res = new HashMap<>();
ReflectionUtils.doWithFields(clz, (field -> {
String val = getFieldValue(clz, field, obj);
if (val != null) {
res.put(getXmlFieldKey(field), val);
}
}));
return res;
}
private static String getXmlFieldKey(Field field) {
String xmlFieldKey = field.getName();
JacksonXmlProperty jacksonXmlProperty = field.getAnnotation(JacksonXmlProperty.class);
if (jacksonXmlProperty != null && jacksonXmlProperty.localName().length() > 0) {
xmlFieldKey = jacksonXmlProperty.localName();
}
return xmlFieldKey;
}
private static String getFieldValue(Class<?> clz, Field field, Object obj) {
String fieldName = field.getName();
try {
PropertyDescriptor pd = new PropertyDescriptor(fieldName, clz);
Method getter = pd.getReadMethod();
Object val = getter.invoke(obj);
if (val == null) {
return null;
}
return val.toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment