开发者社区> 问答> 正文

JSON字符串转javaModel对象错误? 报错

"

import java.util.List;

public class PersonTest {

private String name;
private Game game;

public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public Game getGame() {
    return game;
}
public void setGame(Game game) {
    this.game = game;
}

}

public class Game {
    private String[] string;

    public String[] getString() {
        return string;
    }

    public void setString(String[] string) {
        this.string = string;
    }
}
public class MTest {
    public static void main(String[] arg) throws IOException{
        String json = "[{\"name\":\"Jack\",\"game\":{\"string\":[\"2\",\"3\"]}},{\"name\":\"Jack\",\"game\":{\"string\":[\"2\",\"3\"]}}]";
        JSONArray jsonobject = JSONArray.fromObject(json);
        List<PersonTest> list1 = (List<PersonTest>)JSONArray.toArray(jsonobject,PersonTest.class);
        for(PersonTest u : list1){
            System.out.println(u.getName());
        }
    }
}

为什么转换不了...报错了,哪里写的有错吗?

Exception in thread "main" java.lang.ClassCastException: [Lm.test.PersonTest; cannot be cast to java.util.List
    at m.test.MTest.main(MTest.java:21)
" ![image.png](https://ucc.alicdn.com/pic/developer-ecology/bf544c421b62412f9e77f930ba00846a.png)

展开
收起
因为相信,所以看见。 2020-05-25 15:58:01 830 0
1 条回答
写回答
取消 提交回答
  • 阿里,我所有的向往

    ArrayList<PersonTest> list1 = (ArrayList<PersonTest>)JSONArray.toList(jsonobject,new PersonTest(),new JsonConfig()); 试试,不知道你用的是哪个jar的json,上面代码用的net.sf.json.JSONArray

    ######

    对象里面还包含着对象,不确定json能不能转.但是我感觉jackson可以,不如,我们去看看hibernate用的什么转的?其实,json to object 是可以自己写方法转的

    ![image.png](https://ucc.alicdn.com/pic/developer-ecology/a50578c34678490ca4dbf0939313efdd.png)
    2020-05-25 22:53:43
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载