JSON:就是一種輕量級的數據交換格式,被廣泛應用於WEB應用程序開發。JSON的簡潔和清晰的層次結構,易於閱讀和編寫;同時也易於機器解析和生成,有效的提升網絡傳輸效率;支持多種語言,很多流行的語言都對JSON格式有着很友好的支持。
JSON對象:就是多個屬性被{}括起來的。
JSON數組:就是包含了多個JSON對象的一個集合,數組是以數組括號[]括起來的。JSON數組並不一定是要相同的JSON對象的集合,也可以是不同的對象。
JSON、JSON對象、JSON對象的區別
JSON是一種數據結構,類型xml;JSON對象則是對JSON的具體體現;JSON數組則是將多個JSON對象進行存儲的一個集合。
JSONObject
JSONObject是根據JSON形式在java中存在的對象映射。各大JSON類庫的JSONObject內部實現也是不太一樣。以fastjson為例,就是實現了Map接口。其使用方式和HashMap並無太大區別。
JSONObject person=new JSONObject();
person.put("id",1); person.put("name","tom"); person.put("age",22);
JSONArray
JSONArray就是存放JSONObject的容器。以fastjson為例,就是實現了List接口,默認創建為ArrayList。
JSONObject p1=new JSONObject();
p1.put("id",1); p1.put("name","tom"); p1.put("age",22); JSONObject p2=new JSONObject(); p2.put("id",2); p2.put("name","jerry"); p2.put("age",20); JSONArray array=new JSONArray(); array.add(p1); array.add(p2);
JSONObject類和JSONArray類繼承JSON類,因此,JSON類中的方法都適用於JSONObject和JSONArray。常用的方法如下:
//將java對象轉換為String的json字符串 String tomJsonStr = JSON.toJSONString(o1); System.out.println(tomJsonStr); String jsonArrayStr = JSON.toJSONString(array); System.out.println(jsonArrayStr); //將json對象轉換為java對象 User user = JSON.toJavaObject(o1, User.class); List list = JSON.toJavaObject(array, List.class); //將String類型的json字符串轉換為json對象 JSONObject jsonObject = JSON.parseObject(tomJsonStr); System.out.println(jsonObject); JSONArray jsonArray = JSON.parseArray(jsonArrayStr); System.out.println(jsonArray); //將String類型的json字符串轉換為java對象 User user1 = JSON.parseObject(tomJsonStr, User.class); System.out.println(user1); List<User> users = JSON.parseArray(jsonArrayStr, User.class); System.out.println(users); //將String類型的json字符串轉換為Map HashMap<String, Object> map = JSON.parseObject(tomJsonStr, new TypeReference<HashMap<String, Object>>() { });