时间:2020-11-14来源:www.pcxitongcheng.com作者:电脑系统城
1.首先要导入json相关的jar包
引入的jar包:
(版本自行定义,可以选用使用人数偏多的版本,这样比较稳定)
commons-beanutils-1.9.2.jar
commons-collections-3.2.1.jar
commons-lang-2.6.jar
commons-logging-1.2.jar
ezmorph-1.0.6.jar
json-lib-2.4-jdk15.jar
jar包的下载可以去下面这个网址搜索:
https://mvnrepository.com/

2.在Eclipse下(也可以是IntelliJ IDEA或者MyEclipse)
新建package和Class(步骤略过,可自行选择名字),这里就使用jsonTest。
以下代码块方法见注释,是将JSONObject转换为HashMap的主要方法,传入参数为一个JSONObject对象,返还值为一个HashMap。
?| 1 2 3 4 5 6 7 8 9 10 11 12 |
//1.將JSONObject對象轉換為HashMap<String,String>public static HashMap<String, String> JsonObjectToHashMap(JSONObject jsonObj){ HashMap<String, String> data = new HashMap<String, String>(); Iterator it = jsonObj.keys(); while(it.hasNext()){ String key = String.valueOf(it.next().toString()); String value = (String)jsonObj.get(key).toString(); data.put(key, value); } System.out.println(data); return data;} |
这个方法是将JSON字符串转换为HashMap,传入参数为一段json格式的字符串,返还一个HashMap。
?| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
//2.将json字符串转换成HashMap<String,String>public static HashMap<String, String> JsonToHashMap(String JsonStrin){ HashMap<String, String> data = new HashMap<String, String>(); try{ // 将json字符串转换成jsonObject JSONObject jsonObject = JSONObject.fromObject(JsonStrin); @SuppressWarnings("rawtypes") Iterator it = jsonObject.keys(); // 遍历jsonObject数据,添加到Map对象 while (it.hasNext()) { String key = String.valueOf(it.next()).toString(); String value = (String) jsonObject.get(key).toString(); data.put(key, value); } }catch (Exception e) { e.printStackTrace(); //JOptionPane.showMessageDialog(null,"ERROR:["+e+"]"); } System.out.println(data); return data; } |
在这里顺便介绍一下Iterator类(迭代器)
迭代器是一种设计模式,它是一个对象,它可以遍历并选择序列中的对象,而开发人员不需要了解该序列的底层结构。迭代器通常被称为“轻量级”对象,因为创建它的代价小。
Java中的Iterator功能比较简单,并且只能单向移动:
(1) 使用方法iterator()要求容器返回一个Iterator。第一次调用Iterator的next()方法时,它返回序列的第一个元素。注意:iterator()方法是java.lang.Iterable接口,被Collection继承。
(2) 使用next()获得序列中的下一个元素。
(3) 使用hasNext()检查序列中是否还有元素。
(4) 使用remove()将迭代器新返回的元素删除。
Iterator是Java迭代器最简单的实现,为List设计的ListIterator具有更多的功能,它可以从两个方向遍历List,也可以从List中插入和删除元素。
3.直接上代码
?| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
package JSON;import java.util.HashMap;import java.util.Iterator;import net.sf.json.JSONObject;public class JsonTest { public static void main(String[] args) { JSONObject jsonObj = new JSONObject(true); String content1 = "aaaaa"; String content2 = "bbbbb"; String content3 = "ccccc"; jsonObj.put("a", content1); jsonObj.put("b", content2); jsonObj.put("c", content3); System.out.println(jsonObj.toString()); JsonObjectToHashMap(jsonObj); String jsonstr = "{name:'王杨',sex:'男',school:'郑州航空工业管理学院'}"; JsonToHashMap(jsonstr); } //1.將JSONObject對象轉換為HashMap<String,String> public static HashMap<String, String> JsonObjectToHashMap(JSONObject jsonObj){ HashMap<String, String> data = new HashMap<String, String>(); Iterator it = jsonObj.keys(); while(it.hasNext()){ String key = String.valueOf(it.next().toString()); String value = (String)jsonObj.get(key).toString(); data.put(key, value); } System.out.println(data); return data; } //2.将json字符串转换成HashMap<String,String> public static HashMap<String, String> JsonToHashMap(String JsonStrin){ HashMap<String, String> data = new HashMap<String, String>(); try{ // 将json字符串转换成jsonObject JSONObject jsonObject = JSONObject.fromObject(JsonStrin); @SuppressWarnings("rawtypes") Iterator it = jsonObject.keys(); // 遍历jsonObject数据,添加到Map对象 while (it.hasNext()) { String key = String.valueOf(it.next()).toString(); String value = (String) jsonObject.get(key).toString(); data.put(key, value); } }catch (Exception e) { e.printStackTrace(); //JOptionPane.showMessageDialog(null,"ERROR:["+e+"]"); } System.out.println(data); return data; } } |
记得修改自己的package名称和 class名称。
4.调用main方法测试
(1)传入参数为JSONObject:

输出结果为:

(2)传入参数为JSON字符串:

输出结果为:

这里可以看到,输出的参数顺序和传入时正好相反。但是输出类型为HashMap,数据存储的格式是以key-value键值对的形式存数于HashMap中的。我们可以通过获取key值来获取到其对应的value。
增加如下代码在main方法最后面:
| 1 2 3 4 5 6 |
System.out.println("");//空格换行//通过对应的key键值,获取valueHashMap<String,String> hashmap = JsonToHashMap(jsonstr);System.out.println("--------通过遍历HashMap输出值:-------");System.out.println("name:"+hashmap.get("name")+",sex:"+hashmap.get("sex")+",school:"+hashmap.get("school")); |
得到如下结果:

结语:
到此基本的方法介绍完毕,其实是依靠了JSONObject这个对象的fromObject()方法。fromObject()方法可以转换的类型很多,可以是map、list、数组等等。运用在自己的项目中时,可以是bean或者model等自定义的类。
?| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
1. List集合转换成json代码List list = new ArrayList();list.add( "first" );list.add( "second" );JSONArray jsonArray2 = JSONArray.fromObject( list );2. Map集合转换成json代码Map map = new HashMap();map.put("name", "json");map.put("bool", Boolean.TRUE);map.put("int", new Integer(1));map.put("arr", new String[] { "a", "b" });map.put("func", "function(i){ return this.arr[i]; }");JSONObject json = JSONObject.fromObject(map);3. Bean转换成json代码JSONObject jsonObject = JSONObject.fromObject(new JsonBean());4. 数组转换成json代码boolean[] boolArray = new boolean[] { true, false, true };JSONArray jsonArray1 = JSONArray.fromObject(boolArray); |
以上类型均可以借用fromObject()方法转换为一个JSONObject类型实例。
json作为轻量级的数据格式,在前后端数据交互时很常见,每个公司应该都有自己的JSON转换方法,是公司常见的工具类。
方便了随后的开发使用。
到此这篇关于java中JSONObject转换为HashMap(方法+main方法调用实例)的文章就介绍到这了
2024-04-11
台式机电脑如何连接外接显示器2024-04-11
小新系列打印机手机配置网络的方法教程2024-04-11
Thinkpad 笔记本F1-F12快捷键分别是什么功能ThinkPad蓝牙鼠标如何配对解答步骤41U5008鼠标驱动官网地址: https://support.lenovo.com/en_US/downloads/detail.page?&LegacyDocID=MIGR-67201 第一种方式是比较传统的:使...
2024-04-11
故障现象: USB设备U盘、移动硬盘等插入后提示无法识别的设备,确认设备本身正常,设备可加电,或插入设备后加电但无任何反应,无法使用。新型号机器多表现为黄色USB接口存在此问题,...
2024-04-11