Java中处理Json数据有哪些方法?
作者:WarmHope
时间:2023-05-07
来源:互联网
浏览:0
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
作者最新文章
思源笔记
2026-09-16 17:42
在线PDF转TXT操作步骤与乱码排查指南
2026-09-04 13:02
PDF加水印后如何检查显示效果?在线工具操作步骤与避坑指南
2026-09-03 13:02
Xshell保持连接不断开及会话文件本地存储路径详解
2026-09-03 06:02
两个PDF怎么合并成一个?在线合并后怎么检查顺序?
2026-09-02 20:00
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多
Windows 10
Windows
Windows 10 是一款微软推出的经典操作系统,拥有硬件兼容性与多任务处理能力。它更偏向把系统状态查看和常用调节动作放在一起,适合需要持续观察和微调设备状态的场景。
极度公式
Windows/macOS/Linux
极度公式是一款跨平台专业LaTeX公式识别编辑软件,支持OCR公式识别和多平台编辑。和使用说明,避免使用,享受完整功能与稳定支持。做扫描整理、文字提取和表格转换时,它能把识别后的处理步骤接得更顺,资料录入这类场景会省下不少时间。
















