The conversion of java bean and map

Keywords: JSON Java

There are many ways to convert JavaBeans and map s, such as:

1. Through ObjectMapper, first convert bean to json, then convert json to map, but this method is relatively convoluted and inefficient. After testing, it takes 12 seconds to cycle 10000 beans!!! Not recommended

2. Through java reflection, get the properties and values of the bean class, and then convert them to the key value pairs corresponding to the map. This method takes the second place, but it's a bit cumbersome

3. Through the method in net.sf.cglib.beans.bean map class, this method is very efficient. The difference between the second method and the net.sf.cglib.beans.BeanMap class is that the cache is used. When the bean is created for the first time, it needs to be initialized, and then the cache is used, so the speed is extremely fast. After testing, the rotation of the loop bean and map is 10000 times, only about 300 milliseconds.

 

Therefore, the third way is recommended. Here is the code:

        /**
	 * Replace object with map
	 * @param bean
	 * @return
	 */
	public static <T> Map<String, Object> beanToMap(T bean) {
		Map<String, Object> map = Maps.newHashMap();
		if (bean != null) {
			BeanMap beanMap = BeanMap.create(bean);
			for (Object key : beanMap.keySet()) {
				map.put(key+"", beanMap.get(key));
			}			
		}
		return map;
	}
	
	/**
	 * Replace the map with a javabean object
	 * @param map
	 * @param bean
	 * @return
	 */
	public static <T> T mapToBean(Map<String, Object> map,T bean) {
		BeanMap beanMap = BeanMap.create(bean);
		beanMap.putAll(map);
		return bean;
	}
	
	/**
	 * Convert list < T > to list < map < string, Object > >
	 * @param objList
	 * @return
	 * @throws JsonGenerationException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
	public static <T> List<Map<String, Object>> objectsToMaps(List<T> objList) {
		List<Map<String, Object>> list = Lists.newArrayList();
		if (objList != null && objList.size() > 0) {
			Map<String, Object> map = null;
			T bean = null;
			for (int i = 0,size = objList.size(); i < size; i++) {
				bean = objList.get(i);
				map = beanToMap(bean);
				list.add(map);
			}
		}
		return list;
	}
	
	/**
	 * Convert list < map < string, Object > > to list < T >
	 * @param maps
	 * @param clazz
	 * @return
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 */
	public static <T> List<T> mapsToObjects(List<Map<String, Object>> maps,Class<T> clazz) throws InstantiationException, IllegalAccessException {
		List<T> list = Lists.newArrayList();
		if (maps != null && maps.size() > 0) {
			Map<String, Object> map = null;
			T bean = null;
			for (int i = 0,size = maps.size(); i < size; i++) {
				map = maps.get(i);
				bean = clazz.newInstance();
				mapToBean(map, bean);
				list.add(bean);
			}
		}
		return list;
	}

Posted by noblegas on Sat, 04 Apr 2020 14:06:23 -0700