把json对象转为java对象报错

/*封装的对象*/
public class Student {
private int name;
private int age;
private Child child;
setter getter方法省略}

public class Child {
private String a;
private String b;
setter getter方法省略
}

public class json {
public static void main(){
String str = "{name:11,age:2,child:[{a:'3',b:'4'}]}";
JSONObject obj = JSONObject.fromObject(str);
Map<String,Class> map = new HashMap<String,Class>();
map.put("child",Child.class);
Student s = (Student)JSONObject.toBean(obj,Student.class,map);
System.out.println(s.getAge());
System.out.println(s.getName());
System.out.println(s.getChild().getA());
System.out.println(s.getChild().getB());
}}
/*报错*/
严重: Method invocation failed.
java.lang.IllegalArgumentException: argument type mismatch
org.apache.commons.beanutils.PropertyUtilsBean.setSimpleProperty(PropertyUtilsBean.java:1759)
at org.apache.commons.beanutils.PropertyUtils.setSimpleProperty(PropertyUtils.java:577)
at net.sf.json.util.PropertySetStrategy$DefaultPropertySetStrategy.setProperty(PropertySetStrategy.java:43)
Exception in thread "main" net.sf.json.JSONException: java.lang.IllegalArgumentException: Cannot invoke com.Student.setChild - argument type mismatch
Caused by: java.lang.IllegalArgumentException: Cannot invoke com.Student.setChild - argument type mismatch

/*说明*/
我用的是json-lib-jdk.jar所需的jar包已经导入,就别在导入包的问题上浪费时间了
最新回答
三分醒七分醉

2024-11-30 08:31:31

参数类型不匹配
JSONObject obj = JSONObject.fromObject(new Student());
试试
追问
new一个空对象有用吗,我是要把字符串转成java对象,不放字符串,放空对象肯定不对
追答
我是举例子,告诉你把参数换成对象,你自己set进去值啊!
追问
我是要转成java对象,你让我set进去值,那我用这个包转干嘛
故事与月有关

2024-11-30 11:09:48

推荐用alibaba的 fastjson
支持级联转换
姑娘不要怕我不是什么好人

2024-11-30 09:19:48

朋友,这问题你最终怎么解决的??同求啊