Java中处理Json数据有哪些方法?
作者:WarmHope
时间:2023-05-07
浏览:2
JavaJson的各种处理一、net.sf.json1、Json转MapJSONObjectjsonObject=JSONObject.fromObject(jsonStr);Mapmap=newHashMap();map.put("code",jsonObject.getInt("code"));2、Json转实体JSONObjectjsonObject=JSONObject.fromObject(jsonStr);ArticleFormarticleForm=(ArticleForm)JSONObje
Java Json的各种处理
一、net.sf.json
1、Json转Map
JSONObject jsonObject = JSONObject.fromObject(jsonStr); Mapmap = new HashMap<>(); map.put("code",jsonObject .getInt("code"));
2、Json转实体
JSONObject jsonObject = JSONObject.fromObject(jsonStr); ArticleForm articleForm = (ArticleForm) JSONObject.toBean(jsonObject , ArticleForm.class);
如果实体中带有List字段,需要指定泛型
MapclassMap = new HashMap (); classMap.put("keywords", String.class); ArticleForm articleForm = (ArticleForm) JSONObject.toBean(data.getJSONObject(i), ArticleForm.class,classMap);
3、Json转集合
Listlist = new ArrayList<>(); JSONArray data = jsonObject.getJSONArray("data"); if (errorCode == 0 && data != null && !data.isEmpty()) { for (int i = 0; i < data.size(); i++) { Map classMap = new HashMap (); classMap.put("keywords", String.class); ArticleForm articleForm = (ArticleForm) JSONObject.toBean(data.getJSONObject(i), ArticleForm.class,classMap); list.add(articleForm); } }
另外一种:
Listlist = new ArrayList<>(); JSONArray data = jsonObject.getJSONArray("data"); if (errorCode == 0 && data != null && !data.isEmpty()) { Map classMap = new HashMap (); classMap.put("keywords", String.class); list = (List ) JSONArray.toArray(data, ArticleForm.class,classMap); }
二、com.alibaba.fastjson
1、Json转Map
JSONObject jsonObject = JSON.parseObject(jsonStr); Mapmap = new HashMap<>(); map.put("code",jsonObject .getInt("code"));
2、Json转实体
ArticleForm articleForm = JSON.parseObject(jsonStr, new TypeReference() {});
3、Json转集合
Listlist = JSON.parseObject(jsonStr,new TypeReference >() {});
Java常用json处理
// String和json的互相转换
String str = "{\"status\":200,\"message\":\"\",\"data\":{\"KmList\":[\"总分\",\"语文\",\"数学\",\"英语\",\"道德与法治\",\"科学基础\"]}}";
System.out.println("str:"+str);
// JSONArray arrays = JSON.parseArray(str); // string转jsonArray
JSONObject jsonObject = JSON.parseObject(str); // string转jsonObject
System.out.println("jsonObject:"+jsonObject);
String s = jsonObject.toJSONString(); // json(object和Array相同)转string
// json转list
作者最新文章
Photoshop自定义图层样式的保存、导入与管理技巧
2026-10-05 14:17
Photoshop蒙版在哪里调出来?蒙版按钮位置及使用教程
2026-09-29 09:53
Photoshop图层阵列怎么做?复制多个图层并整齐排列
2026-09-22 16:42
3dmax动画技巧总结:动画制作步骤与渲染视频教程
2026-09-22 14:47
在线PDF转TXT操作步骤与乱码排查指南
2026-09-04 13:02
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多










































