一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

JAVA中JSONObject对象和Map对象之间的相互转换代码示例

时间:2021-01-14 编辑:袖梨 来源:一聚教程网

本篇文章小编给大家分享一下JAVA中JSONObject对象和Map对象之间的相互转换代码示例,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。

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 data =new HashMap<>();
//循环转换
 Iterator it =obj.entrySet().iterator();
 while (it.hasNext()) {
  Map.Entry entry = (Entry) 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 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"}]}

热门栏目