首先声明一下,jsonlib转换与GSON相比太差劲了,操作不是一般的繁琐。GSON可以直接转换成各种集合与对象类型。强烈推荐使用GSON。而且GSON一个方法就可以解决,jsonlib转来转去太繁琐了。
手动创建JSONObject与JSONArray有用,用于读取文件对字符串进行处理
-----------------------------jsonlib操作复杂,转换Map与list<map>更是复杂----------------
Jar包
User.java
1 package TestJson_JSONlib; 2 3 public class User { 4 5 private String id; 6 private String name; 7 private Integer age; 8 private String address; 9 public String getId() { 10 return id; 11 } 12 public int getAge() { 13 return age; 14 } 15 16 public void setAge(Integer age) { 17 this.age = age; 18 } 19 public String getAddress() { 20 return address; 21 } 22 public void setAddress(String address) { 23 this.address = address; 24 } 25 public void setId(String id) { 26 this.id = id; 27 } 28 public String getName() { 29 return name; 30 } 31 public void setName(String name) { 32 this.name = name; 33 } 34 public User() { 35 } 36 public User(String id, String name, Integer age, String address) { 37 super(); 38 this.id = id; 39 this.name = name; 40 this.age = age; 41 this.address = address; 42 } 43 @Override 44 public String toString() { 45 return "User [id=" + id + ", name=" + name + ", age=" + age + ", address=" + address + "]"; 46 } 47 48 49 50 51 }
1.Java对象转json(操作复杂)
对象类型用JSONObject,集合类型用JSONArray。
package TestJson_JSONlib; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.bind.UnmarshallerHandler; import org.junit.Test; import net.sf.json.JSONArray; import net.sf.json.JSONObject; public class Bean2JSON { // 测试单个对象转JSON,转单个对象用JSONObject @Test public void test1(){ User user = new User("1", "QIAOZHI",25,"山西太原"); JSONObject jsonObject = JSONObject.fromObject(user); String json = jsonObject.toString(); System.out.println(json); //{"id":"1","name":"QIAOZHI","age":25,"address":"山西太原"} } // 测试list转JSON,转集合用JSONArray,会产生[] @Test public void test2(){ List<User> list = new ArrayList<User>(); list.add(new User("1", "QIAOZHI",25,"山西太原")); list.add(new User("2", "QIAOZHI",25,"山西太原")); list.add(new User("3", "QIAOZHI",25,"山西太原")); JSONArray jsonArray = JSONArray.fromObject(list); String json = jsonArray.toString(); System.out.println(json); // [{"id":"1","name":"QIAOZHI","age":25,"address":"山西太原"},{"id":"2","name":"QIAOZHI","age":25,"address":"山西太原"},{"id":"3","name":"QIAOZHI","age":25,"address":"山西太原"}] } // 测试map对象转JSON,转单个对象用JSONObject @Test public void test3(){ Map<String,User> map = new HashMap<String,User>(); map.put("1", new User("1", "QIAOZHI",25,"山西太原")); map.put("2", new User("2", "QIAOZHI",25,"山西太原")); map.put("3", new User("3", "QIAOZHI",25,"山西太原")); JSONObject jsonObject= JSONObject.fromObject(map); String json = jsonObject.toString(); System.out.println(json); // {"3":{"address":"山西太原","age":25,"id":"3","name":"QIAOZHI"},"2":{"address":"山西太原","age":25,"id":"2","name":"QIAOZHI"},"1":{"address":"山西太原","age":25,"id":"1","name":"QIAOZHI"}} } // 测试list<map>对象转JSON,转集合用JSONArray,会产生[] @Test public void test4(){ List<Map<String,User>> list = new ArrayList<>(); Map<String,User> map1 = new HashMap<String,User>(); Map<String,User> map2 = new HashMap<String,User>(); map1.put("map11", new User("1", "QIAOZHI",25,"山西太原")); map1.put("map12", new User("2", "QIAOZHI",25,"山西太原")); map2.put("21", new User("11", "QIAOZHI",25,"山西太原")); map2.put("22", new User("21", "QIAOZHI",25,"山西太原")); list.add(map1); list.add(map2); JSONArray jsonArray = JSONArray.fromObject(list); String json = jsonArray.toString(); System.out.println(json); // [{"map12":{"id":"2","name":"QIAOZHI","age":25,"address":"山西太原"},"map11":{"id":"1","name":"QIAOZHI","age":25,"address":"山西太原"}},{"21":{"id":"11","name":"QIAOZHI","age":25,"address":"山西太原"},"22":{"id":"21","name":"QIAOZHI","age":25,"address":"山西太原"}}] } }
2.JSON字符串转Java对象与list(只测了转bean与list)
转出来的中间还有空格,使用时候还得去空格。太繁琐了。
在将 Json 形式的字符串转换为 JavaBean 的时候需要注意 JavaBean 中必须有无参构造函数,否则会报找不到初始化方法的错误。
package TestJson_JSONlib; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Test; import com.google.gson.Gson; import net.sf.json.JSONArray; import net.sf.json.JSONObject; public class JSON2Bean { // 测试json转单个对象 @Test public void test1(){ String json = "{\"id\":\"1\",\"name\":\"QIAOZHI\",\"age\":25,\"address\":\"山西太原\"}"; JSONObject jsonObject = JSONObject.fromObject(json); System.out.println(jsonObject); //产生一个json格式的json对象 // {"id":"1","name":"QIAOZHI","age":25,"address":"山西太原"} User user = (User) JSONObject.toBean(jsonObject, User.class); System.out.println(user); // User [id=1, name=QIAOZHI, age=null, address=山西太原] } // 测试JSON转list(太反复杂了) @SuppressWarnings("unchecked") @Test public void test2(){ String json = "[{'id':'1','name':'QIAOZHI','age':25,'address':'山西太原'},{'id':'2','name':'QIAOZHI','age':25,'address':'山西太原'},{'id':'3','name':'QIAOZHI','age':25,'address':'山西太原'}]"; List<User> list = new ArrayList<User>(); JSONArray jsonArray = JSONArray.fromObject(json); System.out.println(jsonArray); //产生一个JSON格式的数组 // [{"id":"1","name":"QIAOZHI","age":25,"address":"山西太原"},{"id":"2","name":"QIAOZHI","age":25,"address":"山西太原"},{"id":"3","name":"QIAOZHI","age":25,"address":"山西太原"}] list = (List<User>) JSONArray.toList(jsonArray,User.class); System.out.println(list); // [User [id=1, name=QIAOZHI, age=null, address=山西太原], User [id=2, name=QIAOZHI, age=null, address=山西太原], User [id=3, name=QIAOZHI, age=null, address=山西太原]] System.out.println(list.get(1)); // User [id=2, name=QIAOZHI, age=null, address=山西太原] } }
3.手动创建JSONObject与JSONArray(用于封装JSON转java对象与List集合)
package TestJson_JSONlib; import org.junit.Test; import net.sf.json.JSONArray; import net.sf.json.JSONObject; public class CreateJSONObject { @Test public void test1(){ // 手动创建一个JSONObject JSONObject jsonObject = new JSONObject(); jsonObject.put("id", "11"); jsonObject.put("name", "qiaozhi"); jsonObject.put("age", 30); jsonObject.put("address", "山西太原"); System.out.println(jsonObject); // {"id":"11","name":"qiaozhi","age":30,"address":"山西太原"} JSONObject jsonObject1 = new JSONObject(); jsonObject1.put("id", "12"); jsonObject1.put("name", "qiaozhi"); jsonObject1.put("age", 30); jsonObject1.put("address", "山西太原"); System.out.println(jsonObject1); // {"id":"12","name":"qiaozhi","age":30,"address":"山西太原"} // 产生一个JSONArray JSONArray jsonArray = new JSONArray(); jsonArray.add(jsonObject); jsonArray.add(jsonObject1); System.out.println(jsonArray); // [{"id":"11","name":"qiaozhi","age":30,"address":"山西太原"},{"id":"12","name":"qiaozhi","age":30,"address":"山西太原"}] // 用上述方法转成Java对象与List集合,用于处理数据 } }
可用于手动封装JSON对象。
补充:JSON字符串转map,与map转json字符串的测试:(其实字符转转map是先转为JSONObject再转为map)
String accessToken = FetchData.getAccessToken();//{"expires_in":7200,"errmsg":"ok","access_token":"94a50870f92230eb8ad8211b4023675c","errcode":0} //*******************************json字符串转map //转为JSONObject JSONObject jsonObject = JSONObject.fromObject(accessToken); //转为Map Map map = (Map) JSONObject.toBean(jsonObject, Map.class); System.out.println(map); //******************************Map转JSON字符串 JSONObject jsonStr = JSONObject.fromObject(map); System.out.println(jsonStr.toString());
结果:
{expires_in=7200, errmsg=ok, access_token=94a50870f92230eb8ad8211b4023675c, errcode=0}
{"expires_in":7200,"errmsg":"ok","access_token":"94a50870f92230eb8ad8211b4023675c","errcode":0}
补充:JSONArray其实是List的子类,转换的时候字符串以[]包裹的可以转为JSONArray,而且要转为JSONArray必须以[ ]开始结束
String jsonStrs = "[{\"customerId\":19,\"customerName\":\"\tXXX有限公司\"},{\"customerId\":5568,\"customerName\":\"\tXXX展有限公司\"}]"; // 字符串转为JSONArray,必须以[开始,以]结束 JSONArray jsonArray = JSONArray.fromObject(jsonStrs); System.out.println(jsonArray.size()); System.out.println(jsonArray.toString()); System.out.println("================================================="); for (int i = 0, length_1 = jsonArray.size(); i < length_1; i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); System.out.println(jsonObject.toString()); } // jsonArray转list System.out.println("================================================="); List list = JSONArray.toList(jsonArray); System.out.println(list);
结果:
2
[{"customerId":19,"customerName":"\tXXX有限公司"},{"customerId":5568,"customerName":"\tXXX展有限公司"}]
=================================================
{"customerId":19,"customerName":"\tXXX有限公司"}
{"customerId":5568,"customerName":"\tXXX展有限公司"}
=================================================
[net.sf.ezmorph.bean.MorphDynaBean@20c8e08f[
{customerName= XXX有限公司, customerId=19}
], net.sf.ezmorph.bean.MorphDynaBean@640edd19[
{customerName= XXX展有限公司, customerId=5568}
]]
查看JSONArray源码:
补充2:其实我们的JSONObject就是Map,我们将字符串转为JSONObject之后数据存入其内置的map中:
String returnedStr = HttpUtils.doGetWithParams(url, params);//{"errmsg":"ok","department":[{"id":1,"createDeptGroup":true,"name":"开发测试","autoAddUser":true}],"errcode":0} // *******************************json字符串转map JSONObject jsonObject = JSONObject.fromObject(returnedStr); if (jsonObject != null && "ok".equals(jsonObject.get("errmsg"))) { return (String) jsonObject.get("department"); } return null;
结果:
[{"id":1,"createDeptGroup":true,"name":"开发测试","autoAddUser":true}]
查看源码:
public Object get( Object key ) { if( key instanceof String ){ return get( (String) key ); } return null; } /** * Get the value object associated with a key. * * @param key A key string. * @return The object associated with the key. * @throws JSONException if this.isNull() returns true. */ public Object get( String key ) { verifyIsNull(); return this.properties.get( key ); }
如果是字符串的话调用字符串调用方法从properties中获取值,properties是什么?应该是个map。。。继续查看源码如下:
/** * The Map where the JSONObject's properties are kept. */ private Map properties;
补充2:如果从JSONObject中获取一个不存在的key的时候会报错,而不是返回null,查看源码发现:
public String getString( String key ) { verifyIsNull(); Object o = get( key ); if( o != null ){ return o.toString(); } throw new JSONException( "JSONObject[" + JSONUtils.quote( key ) + "] not found." ); }
解决办法:先判断一下
if(jo.containsKey("tel")){ userMap.put("officePhone", jo.getString("tel")); }
而对于HashMap来说,key不存在是返回null的,源码如下:
public V get(Object key) { if (key == null) return getForNullKey(); Entry<K,V> entry = getEntry(key); return null == entry ? null : entry.getValue(); }
总结:
1.字符串转JSONArray的时候字符串必须是JSON数组,也就是[{},{},.....];字符串转JSONObject必须是对象,也就是{"key":"value"...},当多个{}{}的时候只会转一个,如下。字符串转JSONArray或者JSONObject调用对应的fromObject(Obj)方法:
String jsonStrs = "[{\"customerId\":19,\"customerName\":\"\tXXX有限公司\"},{\"customerId\":5568,\"customerName\":\"\tXXX展有限公司\"}]"; String jsonStrs1 = "{\"customerId\":19,\"customerName\":\"\tXXX有限公司\"},{\"customerId\":5568,\"customerName\":\"\tXXX展有限公司\"}"; JSONArray fromObject = JSONArray.fromObject(jsonStrs); JSONObject fromObject1 = JSONObject.fromObject(jsonStrs1); System.out.println(fromObject.toString()); System.out.println(fromObject1.toString());
结果:
[{"customerId":19,"customerName":"\tXXX有限公司"},{"customerId":5568,"customerName":"\tXXX展有限公司"}]
{"customerId":19,"customerName":"\tXXX有限公司"}
2.JSONObject是一个中间对象。如果操作集合调用对应的JSONArray即可。
字符串转对象可以先调用JSONObject.fromObject(str)转换为JSONObject,然后调用JSONObject.toBean(jsonObject,class)转为对应类型的对象
对象转JSON字符串可以JSONObject.fromObject(str)转换为JSONObject,然后调用其toString()方法即可。
Map map = new HashMap<>(); map.put("x", "x"); map.put("y", "y"); // Map转JSON字符串(先为JSONObject) JSONObject fromObject = JSONObject.fromObject(map);// 转为JSONObject String jsonStr = fromObject.toString(); System.out.println(jsonStr); System.out.println("=========================="); // JSON转Map字符串(先转为JSONObject) JSONObject fromObject2 = JSONObject.fromObject(jsonStr); Map bean = (Map) JSONObject.toBean(fromObject2, Map.class); System.out.println(bean);
结果:
{"y":"y","x":"x"}
==========================
{y=y, x=x}
补充:上面的JSONObject是JSONLib下的类。如果是fastjson包下的JSONObject(alibaba的)使用更简单,字符串转对象与对象转字符串如下:
toJSONString(bean)转为JSON串,parseObject(jsonStr,class)转为Bean。
Map map = new HashMap<>(); map.put("x", "x"); map.put("y", "y"); // bean转JSON字符串 String jsonString = com.alibaba.fastjson.JSONObject.toJSONString(map); System.out.println(jsonString); // JSON字符串转bean Map parseObject = com.alibaba.fastjson.JSONObject.parseObject(jsonString, Map.class); System.out.println(parseObject);
也可以指定指定属性不进行序列化,如下:
Map<String, String> map = new HashMap<>(); map.put("x", "x"); map.put("y", "y"); // 采用过滤器过滤掉指定属性 SimplePropertyPreFilter filter = new SimplePropertyPreFilter(); filter.getExcludes().add("x"); String jsonString2 = com.alibaba.fastjson.JSONObject.toJSONString(map, filter); System.out.println(jsonString2);
结果:
{"y":"y"}