fastjson:map转json字符串、json字符串转map、map根据key名拿value、JSONArray转list

  • A+
所属分类:Java

1、map转json字符串:

List<SiteBean> list = new ArrayList();

list.add(siteBean);

list.add(siteBean);

 

Map<String,Object> map = new HashMap<>();

map.put("resultCode","0");

map.put("resultMsg","成功");

map.put("resultData",list);

map.put("count",list.size());

String jsonStr = new JSONObject(map).toString();

得到的jsonStr如下:

{"resultData":[{"abbr":"abbrOf11","begTime":"begTimeOf11","name":"nameOf11","objId":"objOf11","parZone":"parZoneOf11","zoneName":"zoneNameOf11"},{"abbr":"abbrOf12","begTime":"begTimeOf12","name":"nameOf12","objId":"objOf12","parZone":"parZoneOf12","zoneName":"zoneNameOf12"}],"resultCode":"0","count":2,"resultMsg":"成功"}

2、json字符串转map

Map<String, Object> map = (Map<String, Object>) JSONObject.parse(resultJsonStr);

map里面的resultData的value是一个JSONArray,JSONArry里面是JSONObject,一个JSONObject对应了一个SiteBean2

3、将map里面键为resultData的值拿出来,拿出的就是2里的JSONArray,再把JSONArray转成对应bean的list

List<SiteBean> siteList = new ArrayList<>();

siteList = (List<SiteBean>) map.get("resultData");

如果不成,可以用下面的方法:

JSONArray jsonArray = (JSONArray) resultMap.get("resultData");

List<SiteBean> list = JSONObject.parseArray(jsonArray.toString(),SiteBean.class);

4、活用,拿json字符串resultData里面只含有一个bean的转换成bean

JSONArray jsonArray = (JSONArray) resultDetailMap.get("resultData");

SiteDetailBean siteDetailBean= JSON.toJavaObject((JSONObject) jsonArray.get(0),SiteDetailBean.class);

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: