packagecom.home.app.common.utils;importcom.fasterxml.jackson.annotation.JsonInclude.Include;importcom.fasterxml.jackson.core.JsonProcessingException;importcom.fasterxml.jackson.databind.ObjectMapper;importcom.fasterxml.jackson.databind.SerializationFeature;importjava.lang.reflect.Field;importjava.lang.reflect.Modifier;importjava.util.LinkedHashMap;importjava.util.Map;/***@authorBinary Wang*/
public classJsonUtils {private static final ObjectMapper JSON = newObjectMapper();static{
JSON.setSerializationInclusion(Include.NON_NULL);
JSON.configure(SerializationFeature.INDENT_OUTPUT, Boolean.TRUE);
}public staticString toJson(Object obj) {try{returnJSON.writeValueAsString(obj);
}catch(JsonProcessingException e) {
e.printStackTrace();
}return null;
}/*** Object转Map
*@paramobj
*@return
*/
public static MapgetObjectToMap(Object obj) {
Map map = new LinkedHashMap();
Class> clazz =obj.getClass();
System.out.println(clazz);for(Field field : clazz.getDeclaredFields()) {
field.setAccessible(true);
String fieldName=field.getName();
Object value= null;try{
value=field.get(obj);
}catch(IllegalAccessException e) {
e.printStackTrace();
}if (value == null){
value= "";
}
map.put(fieldName, value);
}returnmap;
}//Map转Object
public static Object getMapToObject(Map map, Class>beanClass) {if (map == null)return null;
Object obj= null;try{
obj=beanClass.newInstance();
}catch(InstantiationException e) {
e.printStackTrace();
}catch(IllegalAccessException e) {
e.printStackTrace();
}
Field[] fields=obj.getClass().getDeclaredFields();for(Field field : fields) {int mod =field.getModifiers();if (Modifier.isStatic(mod) ||Modifier.isFinal(mod)) {continue;
}
field.setAccessible(true);if(map.containsKey(field.getName())) {try{
field.set(obj, map.get(field.getName()));
}catch(IllegalAccessException e) {
e.printStackTrace();
}
}
}returnobj;
}
}