JSONObject与JSONArray的使用1
一、JAR包简介
要使程序可以运行必须引入JSON-lib包,JSON-lib包同时依赖于以下的JAR包:
1.commons-lang.jar
2.commons-beanutils.jar
3.commons-collections.jar
4.commons-logging.jar
5.ezmorph.jar
6.json-lib-2.2.2-jdk15.jar
二、JSONObject(json对象),JSONArray(json数组)的创建
import java.util.ArrayList; import java.util.HashMap; import net.sf.json.JSONArray; import net.sf.json.JSONObject; public class Test { public static void main(String[] args) { //JsonObject和JsonArray区别就是JsonObject是对象形式,JsonArray是数组形式 //创建JsonObject第一种方法 JSONObject jsonObject = new JSONObject(); jsonObject.put("UserName", "xxb"); jsonObject.put("age", "27"); System.out.println("jsonObject1:" + jsonObject); //创建JsonObject第二种方法 HashMap<String, String> hashMap = new HashMap<String, String>(); hashMap.put("UserName", "xxb"); hashMap.put("age", "27"); System.out.println("jsonObject2:" + JSONObject.fromObject(hashMap)); //创建一个JsonArray方法1 JSONArray jsonArray = new JSONArray(); jsonArray.add(0, "xxb"); jsonArray.add(1, "27"); System.out.println("jsonArray1:" + jsonArray); //创建JsonArray方法2 ArrayList<String> arrayList = new ArrayList<String>(); arrayList.add("xxb"); arrayList.add("27"); System.out.println("jsonArray2:" + JSONArray.fromObject(arrayList)); //如果JSONArray解析一个HashMap,则会将整个对象的放进一个数组的值中 System.out.println("jsonArray FROM HASHMAP:" + JSONArray.fromObject(hashMap)); //组装一个复杂的JSONArray JSONObject jsonObject2 = new JSONObject(); jsonObject2.put("UserName", "xxb"); jsonObject2.put("age", "27"); jsonObject2.element("Array", arrayList); System.out.println("jsonObject2:" + jsonObject2); } }
结果:
jsonObject1:{"UserName":"xxb","age":"27"}
jsonObject2:{"age":"27","UserName":"xxb"}
jsonArray1:["xxb","27"]
jsonArray2:["xxb","27"]
jsonArray FROM HASHMAP:[{"age":"27","UserName":"xxb"}]
jsonObject2:{"UserName":"ZHULI","age":"30","Array":["ZHULI","30","ALI"]}
二、解析JSON字符串
import net.sf.json.JSONArray; import net.sf.json.JSONObject; public class Test { public static void main(String[] args) { String jsonString = "{\"UserName\":\"xxb\",\"age\":\"27\",\"Array\":[\"xxb\",\"27\"]}"; //将Json字符串转为java对象 JSONObject obj = JSONObject.fromObject(jsonString); //获取Object中的UserName if (obj.has("UserName")) { System.out.println("UserName:" + obj.getString("UserName")); } //获取ArrayObject if (obj.has("Array")) { JSONArray transitListArray = obj.getJSONArray("Array"); for (int i = 0; i < transitListArray.size(); i++) { System.out.print("Array:" + transitListArray.getString(i) + " "); } } } }
结果:
UserName:xxb
Array:xxb Array:27