import com.google.gson.Gson;
public class Beanutil {
public static void main(String args[]) {
Map<String, Object> yourMap = new HashMap<String, Object>();
yourMap.put("name", "Joan");
yourMap.put("age", "309");
Map<String, Object> secondMap = new HashMap<String, Object>();
secondMap.put("name", "k");
secondMap.put("age", "39");
yourMap.put("bean",secondMap);
YourBean bean = null;
try {
bean= new YourBean();
try{
BeanUtils.populate(bean, yourMap);
}catch(Exception e){
e.printStackTrace();
}
System.out.println(new Gson().toJson(bean));
} catch (Throwable e) {
e.getMessage();
}
}
}
bean类如下:
public class YourBean {
String name = null;
int age = 0;
public Bean2 bean;
//getter & setters
}
public class Bean2 {
String name = null;
int age = 0;
//getter and setters
}
获得例外
java.lang.IllegalArgumentException:无法调用 bean类'class上的com.org.nlp.test.YourBean.setBean com.org.nlp.test.YourBean' - 参数类型不匹配 - 有对象 类型“java.util.HashMap”但预期签名 “com.org.nlp.test.Bean2”at org.apache.commons.beanutils.PropertyUtilsBean.invokeMethod(PropertyUtilsBean.java:2195) 在 org.apache.commons.beanutils.PropertyUtilsBean.setSimpleProperty(PropertyUtilsBean.java:2108) 在 org.apache.commons.beanutils.PropertyUtilsBean.setNestedProperty(PropertyUtilsBean.java:1914) 在 org.apache.commons.beanutils.PropertyUtilsBean.setProperty(PropertyUtilsBean.java:2021) 在 org.apache.commons.beanutils.BeanUtilsBean.setProperty(BeanUtilsBean.java:1018) 在 org.apache.commons.beanutils.BeanUtilsBean.populate(BeanUtilsBean.java:823) 在 org.apache.commons.beanutils.BeanUtils.populate(BeanUtils.java:431) 在 com.org.nlp.test.Beanutil.main(Beanutil.java:24) 引起:java.lang.IllegalArgumentException:参数类型不匹配 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 在 sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 在java.lang.reflect.Method.invoke(Method.java:498)at org.apache.commons.beanutils.PropertyUtilsBean.invokeMethod(PropertyUtilsBean.java:2127) ... 7更多{“name”:“Joan”,“age”:309}
我很喜欢
{name=Joan, age=309, bean={name=k, age=39}}
请帮我解决这个问题并建议我,如果他们有更好的方法
提前致谢
答案 0 :(得分:1)
根据错误消息,您似乎需要首先填充内部Bean2:
BeanUtils.populate(bean2, secondMap);
将填充的bean添加到地图:
yourMap.put("bean",bean2);
然后最后填充bean:
BeanUtils.populate(bean, yourMap);
这样,yourMap包含填充的Bean2成员,并且不需要执行嵌套填充。
答案 1 :(得分:1)
Actualy我需要这样,我们可以使用jackson-databind
final ObjectMapper mapper = new ObjectMapper();
bean = mapper.convertValue(yourMap, YourBean.class);