Redis 存取List (补坑 一)

List<Dog> dogLists = new ArrayList<>(
        Arrays.asList(new Dog(1,"xiaobai"),new Dog(2,"xiaohua")) );
r.set("dog", JSONObject.toJSONString(dogLists));
System.out.println("list对象转json保存成功");
List<Dog> ddLists = null;
String d = r.get("dog");
List<Dog> dLists = (List<Dog>)JSONObject.parse(d);
List<Dog> dogs1 = JSONObject.parseArray(d, Dog.class);
List<Dog> dogs = JSONArray.parseArray(d, Dog.class);

1.存进redis 没有问题,data redis manager 可视化工具可以查看到key 是dog的信息

2.取出来时dLists 是一个JSONArray 不是ArrayList,获取对象信息时报错:

com.alibaba.fastjson.JSONObject cannot be cast to com.stylefeng.guns.modular.system.transfer.Dog

3.知道了是JSONArray对象就想着转成ArrayList 类型

4.dogs1,dogs就是代码没有错误,错误错在Dog类只创立了两个有参数构造函数,没有生成无参构造函数,在程序运行时报错:

com.alibaba.fastjson.JSONException: default constructor not found. class com.stylefeng.guns.modular.system.transfer.Dog

这个的原因是少了无参构造函数,添加上就解决了

5.public Dog(){};

猜你喜欢

转载自blog.csdn.net/Zsigner/article/details/86040307