软件编程
位置:首页>> 软件编程>> java编程>> JAVA中JSONObject对象和Map对象之间的相互转换

JAVA中JSONObject对象和Map对象之间的相互转换

作者:欢乐的八爪鱼  发布时间:2023-07-13 15:04:28 

标签: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<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"}]}

来源:https://blog.csdn.net/gm371200587/article/details/101268078

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com