在项目中,我将实体类转成json字符串使用hset方式存入redis:
redisService.hset("deviceSetting:"+deviceSettingDto.getDeviceId(),"settingId:"+deviceSettingDto.getId(), JSON.toJSONString(one));
取出的时候使用JSON.parseObject()解析报如下错误:
com.alibaba.fastjson.JSONException: syntax error, expect {, actual string, pos 0, fastjson-version 1.2.47
at com.alibaba.fastjson.parser.deserializer.JavaBeanDeserializer.deserialze(JavaBeanDeserializer.java:451)
at com.alibaba.fastjson.parser.deserializer.JavaBeanDeserializer.parseRest(JavaBeanDeserializer.java:1283)
at com.alibaba.fastjson.parser.deserializer.FastjsonASMDeserializer_1_Users.deserialze(Unknown Source)
at com.alibaba.fastjson.parser.deserializer.JavaBeanDeserializer.deserialze(JavaBeanDeserializer.java:267)
at com.alibaba.fastjson.parser.DefaultJSONParser.parseObject(DefaultJSONParser.java:661)
at com.alibaba.fastjson.JSON.parseObject(JSON.java:365)
at com.alibaba.fastjson.JSON.parseObject(JSON.java:269)
at com.alibaba.fastjson.JSON.parseObject(JSON.java:488)
错误原因:
字符串存入redis会加上\导致解析失败,解决方式直接将对象存入redis,取出的时候就可以直接解析了,下面是两种存储方式,第一行是存的字符串,第二行存的是对象
下面是解析方式:
List<Object> hvals = redisService.hvals("deviceSetting:" + 2);
System.out.println(JSON.toJSONString(hvals,true));
List<DeviceSetting> deviceSettingList = hvals.stream().map(obj -> JSON.parseObject(JSON.toJSONString(obj), DeviceSetting.class)).collect(Collectors.toList());
System.out.println(JSON.toJSONString(deviceSettingList,true));
解析结果