private static Logger logger = LoggerFactory.getLogger(JsonUtil.class);
/* Map <-> Json */ public static Map<String, Object> convertJsonToMap(String json) { ObjectMapper objectMapper = new ObjectMapper(); try { TypeReference<Map<String, Object>> typeReference = new TypeReference<Map<String, Object>>() { }; return objectMapper.readValue(json, typeReference); } catch (IOException e) { logger.error("Error converting Json to Map .", e); } return null; }
public static String convertMapToJson(Map<String, Object> map) { try { return new ObjectMapper().writeValueAsString(map); } catch (JsonProcessingException e) { logger.error("Error converting Map to JSon .", e); } return null; }
public static String convertObjectToJson(Object obj) { return convertMapToJson(converObjectToMap(obj)); }
public static Object convertJsonToObject(String jsonString, Object objClass) { return convertMapToObject(convertJsonToMap(jsonString), objClass); }
public static Map<String, Object> converObjectToMap(Object obj){ try { Field[] fields = obj.getClass().getDeclaredFields(); Map resultMap = new HashMap(); for(int i=0; i<=fields.length-1;i++){ fields[i].setAccessible(true); resultMap.put(fields[i].getName(), fields[i].get(obj)); } return resultMap; } catch (IllegalArgumentException e) { logger.error("Error convert Object to Map ." , e); } catch (IllegalAccessException e) { logger.error("Error convert Object to Map ." , e); } return null; }
public static Object convertMapToObject(Map map, Object objClass){ String keyAttribute = null; String setMethodString = "set"; String methodString = null; Iterator itr = map.keySet().iterator(); while(itr.hasNext()){ keyAttribute = (String) itr.next(); methodString = setMethodString+keyAttribute.substring(0,1).toUpperCase()+keyAttribute.substring(1); try { Method[] methods = objClass.getClass().getDeclaredMethods(); for(int i=0;i<=methods.length-1;i++){ if(methodString.equals(methods[i].getName())){ System.out.println("invoke : "+methodString); methods[i].invoke(objClass, map.get(keyAttribute)); } } } catch (SecurityException e) { logger.error("SecurityException convert Map to Object .",e ); } catch (IllegalAccessException e) { logger.error("IllegalAccessException convert Map to Object .",e ); } catch (IllegalArgumentException e) { logger.error("IllegalArgumentException convert Map to Object .",e ); } catch (InvocationTargetException e) { logger.error("InvocationTargetException convert Map to Object .",e ); } } return objClass; } |