本文目录一览:
Java怎样把这种类型转成Map?
这个需要你遍历这个数据结构,然后进行相应的赋值操作就可以了。只要了解数据结构就行。
java中怎么将实体转为map
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
/**
* java实体类转换为map
* @author vic
*/
public class JavaBeanUtil {
public static Map<String, Object> convertBeanToMap(Object bean) throws IntrospectionException, IllegalAccessException, InvocationTargetException {
Class<?> type = bean.getClass();
Map<String, Object> returnMap = new HashMap<>();
BeanInfo beanInfo = Introspector.getBeanInfo(type);
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (int i = 0; i < propertyDescriptors.length; i++) {
PropertyDescriptor descriptor = propertyDescriptors[i];
String propertyName = descriptor.getName();
if (!propertyName.equals("class")) {
Method readMethod = descriptor.getReadMethod();
Object result = readMethod.invoke(bean, new Object[0]);
if (result != null) {
returnMap.put(propertyName, result);
} else {
returnMap.put(propertyName, "");
}
}
}
return returnMap;
}
}
java中怎么list 转成 map?
可以转换的,你用循环把list中的数据读出来:
Iterator it = list().iterator();
while (it.hasNext()) {
对象类型 XX = (对象类型) it.next();
}
然后再把对象放到map里面就行了。
Java中 如何把Object类型强转成Map类型
首先你需要保证要转换的Object的实际类型是Map<String, String>
。
假设Object变量名为obj
,强制转换:
(Map<String, String>) obj
转换前最好进行类型检查,防止出现ClassCastException
。
JAVA中String如何转为Map
/**
* String转换Map
*
* @param mapText
* :需要转换的字符串
* @param KeySeparator
* :字符串中的分隔符每一个key与value中的分割
* @param ElementSeparator
* :字符串中每个元素的分割
* @return Map<?, ?>
*/
public static Map<String, Object> StringToMap(String mapText) {
if (mapText == null || mapText.equals("")) {
return null;
}
mapText = mapText.substring(1);
mapText = EspUtils.DecodeBase64(mapText);
Map<String, Object> map = new HashMap<>();
String[] text = mapText.split("\\" + SEP2); // 转换为数组
for (String str : text) {
String[] keyText = str.split(SEP1); // 转换key与value的数组
if (keyText.length < 1) {
continue;
}
String key = keyText[0]; // key
String value = keyText[1]; // value
if (value.charAt(0) == 'M') {
Map<?, ?> map1 = StringToMap(value);
map.put(key, map1);
} else if (value.charAt(0) == 'L') {
List<?> list = StringToList(value);
map.put(key, list);
} else {
map.put(key, value);
}
}
return map;
}