一、用法
1.序列化—将Object转为Json对象
Object data=JSON.toJSON( MyObject );
注:本文的Object可以是Map、List、javaBean等
需求:请拼接如下json
{ "openid": [ "o1Pj9jmZvwSyyyyyyBa4aULW2mA", "o1Pj9jmZvxxxxxxxxxULW2mA" ], "username": [ "afdvvf", "abcd" ] }
代码:
Map<String,List<String>> postDataMap= new HashMap<String,List<String>>(); postDataMap.put("openid", openIdList); postDataMap.put("username", userNameList); Object data=JSON.toJSON(postDataMap); system.out.println(data.toString());
2.序列化—将Object转为Json字符串
String data=JSON.toJSONString(MyObject);
需求:请拼接如下字符串:
{}
代码:
Object ob=new Object(); String data=JSON.toJSONString(ob); System.out.println(data);
3.反序列化—将json字符串转为JSONObject
JSONObject jsonObject=JSON.parseObject(str);
Data data = JSON.parseObject(str, Data.class);
需求:将以下Json字符串转为JSONObject
{ "openid": [ "o1Pj9jmZvwSyyyyyyBa4aULW2mA", "o1Pj9jmZvxxxxxxxxxULW2mA" ], "username": [ "afdvvf", "abcd" ] }
代码:
String str="{ " + " "openid": [ " + " "o1Pj9jmZvwSyyyyyyBa4aULW2mA", " + " "o1Pj9jmZvxxxxxxxxxULW2mA" " + " ], " + " "username": [ " + " "afdvvf", " + " "abcd" " + " ] " + " }"; JSONObject jsonObject=JSON.parseObject(str); System.out.println(jsonObject.toJSONString());
4.通过JSONObject构造json字符串
JSONObject jsonObject=new JSONObject(); jsonObject.put(key, value);
需求:请构造如下json字符串
{ "money": 123, "s_pappid": "djwhei124" }
代码:
JSONObject jsonObject=new JSONObject(); jsonObject.put("s_pappid", "djwhei124"); jsonObject.put("money", 123); System.out.println(jsonObject.toJSONString());