java对象和json常见的互转

在之前的博客中有介绍到如何把HttpEntity转为json:https://blog.csdn.net/duan196_118/article/details/107353704。今天来总结下java对象与json之间的互转。项目中,使用缓存来减少服务器的压力,常常会把java对象转为json进行存储,读取的时候再转为java对象,便于前台的展示。当然这里只是其中一个常见的场景。高手可以忽略,不喜勿喷!!!

1.把java对象转为json字符串

​
        BigPcEntry bigPcEntry = zbBigPcService.getBigPcMsg();
        String tjJson = JSONObject.fromObject(bigPcEntry).toString();

​

2. 把json字符串转为java对象

 BigPcEntry bp = JSONObject.parseObject(tjJson, BigPcEntry.class);

3.把java对象集合转为json对象数组

 String listJson = JSONArray.fromObject(list2).toString();
 //list2是需要转换的对象集合

4. 吧json对象数组转为java对象集合

 List<ComProVo> bp = JSONObject.parseArray(listJson, ComProVo.class);
 //ComProVo为集合对象类型

推荐一款比较实用的json在线工具: http://www.bejson.com/json2javapojo/

猜你喜欢

转载自blog.csdn.net/duan196_118/article/details/110873898