bean和map轉換的程式碼(參考)
阿新 • • 發佈:2020-08-28
原文:https://www.jianshu.com/p/70a626f83336
1 /** 2 * 將物件裝換為map 3 * 4 * @param bean 5 * @return 6 */ 7 public static <T> Map<String, Object> beanToMap(T bean) { 8 Map<String, Object> map = Maps.newHashMap(); 9 if (bean != null) { 10 BeanMap beanMap = BeanMap.create(bean);11 for (Object key : beanMap.keySet()) { 12 map.put(key + "", beanMap.get(key)); 13 } 14 } 15 return map; 16 } 17 18 /** 19 * 將map裝換為javabean物件 20 * 21 * @param map 22 * @param bean 23 * @return 24 */ 25 publicstatic <T> T mapToBean(Map<String, Object> map, T bean) { 26 BeanMap beanMap = BeanMap.create(bean); 27 beanMap.putAll(map); 28 return bean; 29 } 30 31 /** 32 * 將List<T>轉換為List<Map<String, Object>> 33 * 34 * @param objList35 * @return 36 * @throws JsonGenerationException 37 * @throws JsonMappingException 38 * @throws IOException 39 */ 40 public static <T> List<Map<String, Object>> objectsToMaps(List<T> objList) { 41 List<Map<String, Object>> list = Lists.newArrayList(); 42 if (objList != null && objList.size() > 0) { 43 Map<String, Object> map = null; 44 T bean = null; 45 for (int i = 0, size = objList.size(); i < size; i++) { 46 bean = objList.get(i); 47 map = beanToMap(bean); 48 list.add(map); 49 } 50 } 51 return list; 52 } 53 54 /** 55 * 將List<Map<String,Object>>轉換為List<T> 56 * 57 * @param maps 58 * @param clazz 59 * @return 60 * @throws InstantiationException 61 * @throws IllegalAccessException 62 */ 63 public static <T> List<T> mapsToObjects(List<Map<String, Object>> maps, Class<T> clazz) 64 throws InstantiationException, IllegalAccessException { 65 List<T> list = Lists.newArrayList(); 66 if (maps != null && maps.size() > 0) { 67 Map<String, Object> map = null; 68 T bean = null; 69 for (int i = 0, size = maps.size(); i < size; i++) { 70 map = maps.get(i); 71 bean = clazz.newInstance(); 72 mapToBean(map, bean); 73 list.add(bean); 74 } 75 } 76 return list; 77 }