如何实现Java中JSONObject与Map对象之间的双向高效转换?
- 内容介绍
- 文章标签
- 相关推荐
本文共计258个文字,预计阅读时间需要2分钟。
1. 将JSON字符串转换为Map对象 例如,JSON字符串:`{ contend: [{ bid: 22, carid: 0 }, { bid: 22, carid: 0 }], result: 100, total: 2 }` 下面是直接输出的代码: java // JSON字符串String jsondata={\contend\:[{\bid\:\22\,\carid\:\0\},{\bid\:\22\,\carid\:\0\}],\result\:100,\total\:2};
1.由json字符串转换成Map对象
如json字符串:{"contend":[{"bid":"22","carid":"0"},{"bid":"22","carid":"0"}],"result":100,"total":2}
下面直接附代码:
//json字符串 String jsondata="{\"contend\":[{\"bid\":\"22\",\"carid\":\"0\"},{\"bid\":\"22\",\"carid\":\"0\"}],\"result\":100,\"total\":2}"; JSONObject obj= JSON.parseObject(jsondata); //map对象 Map<String, Object> data =new HashMap<>(); //循环转换 Iterator it =obj.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, Object> entry = (Entry<String, Object>) it.next(); data.put(entry.getKey(), entry.getValue()); } System.out.println("map对象:"+data.toString());
下面是输出内容:
{total=2, contend=[{"carid":"0","bid":"22"},{"carid":"0","bid":"22"}], result=100}
2.由Map对象转换成json字符串
//map对象 Map<String, Object> data =new HashMap<>(); String x =JSONObject.toJSONString(data); System.out.println("json字符串:"+x);
下面是输出内容:
{"total":2,"result":100,"contend":[{"carid":"0","bid":"22"},{"carid":"0","bid":"22"}]}
到此这篇关于JAVA中JSONObject对象和Map对象之间的相互转换的文章就介绍到这了,更多相关JAVA JSONObject和Map相互转换内容请搜索易盾网络以前的文章或继续浏览下面的相关文章希望大家以后多多支持易盾网络!
本文共计258个文字,预计阅读时间需要2分钟。
1. 将JSON字符串转换为Map对象 例如,JSON字符串:`{ contend: [{ bid: 22, carid: 0 }, { bid: 22, carid: 0 }], result: 100, total: 2 }` 下面是直接输出的代码: java // JSON字符串String jsondata={\contend\:[{\bid\:\22\,\carid\:\0\},{\bid\:\22\,\carid\:\0\}],\result\:100,\total\:2};
1.由json字符串转换成Map对象
如json字符串:{"contend":[{"bid":"22","carid":"0"},{"bid":"22","carid":"0"}],"result":100,"total":2}
下面直接附代码:
//json字符串 String jsondata="{\"contend\":[{\"bid\":\"22\",\"carid\":\"0\"},{\"bid\":\"22\",\"carid\":\"0\"}],\"result\":100,\"total\":2}"; JSONObject obj= JSON.parseObject(jsondata); //map对象 Map<String, Object> data =new HashMap<>(); //循环转换 Iterator it =obj.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, Object> entry = (Entry<String, Object>) it.next(); data.put(entry.getKey(), entry.getValue()); } System.out.println("map对象:"+data.toString());
下面是输出内容:
{total=2, contend=[{"carid":"0","bid":"22"},{"carid":"0","bid":"22"}], result=100}
2.由Map对象转换成json字符串
//map对象 Map<String, Object> data =new HashMap<>(); String x =JSONObject.toJSONString(data); System.out.println("json字符串:"+x);
下面是输出内容:
{"total":2,"result":100,"contend":[{"carid":"0","bid":"22"},{"carid":"0","bid":"22"}]}
到此这篇关于JAVA中JSONObject对象和Map对象之间的相互转换的文章就介绍到这了,更多相关JAVA JSONObject和Map相互转换内容请搜索易盾网络以前的文章或继续浏览下面的相关文章希望大家以后多多支持易盾网络!

