使用jackson获取复杂对象中的成员变量对象
在Java中进行远程请求时, 获取到复杂对象中的成员变量为某个对象,直接使用ObjectMapper.readValue() 无法再次获取到其中的成员变量的对象.
例如:下面的json串中data为item对象, 整个json串为 为了方便网络传输包装item后的新对象result.
{"status":200,"msg":"OK","data":{"created":1425821598000,"updated":1425821598000,"itemId":536563,"itemDesc":"\t<style>.bigapic{ width:750px; height:auto;}</style>"},"ok":true}
在经过ObjectMapper.readValue() 解析后,可以获取到result对象.原以为使用类型转换(Item)result.getData() 可以获取到item对象. 但是在运行时,报出了类型转换异常,提示不能从LinkedHashMap转换为Item类的异常.
开始检查data内封装的对象,发现就是Item.
于是尝试使用下面的方式:
JsonNode readTree = objectMapper.readTree(result); // 将result转为json对象
itemDesc=objectMapper.readValue(readTree.get(“data”).toString(), ItemDesc.class); //通过json对象获取到data节点的数据,通过toString方法再次转为json串. 使用ObjectMapper再解析data的json串.
结果成功了. 但是这种方法还是麻烦,好像gson可以直接转换, 目前还没有用过gson.
还没有评论,来说两句吧...