1、 目前解析json有三種工具:org.json(Java經常使用的解析),fastjson(阿里巴巴工程師開發的),Gson(Google官網出的),其中解析速度最快的是Gson。html
3種json工具下載目錄爲:http://download.csdn.net/detail/hebao5201314/9491742java
2、org.json是Java經常使用的JSON數據解析,主要提供JSONObject和JSONArray類,如今就各個類的使用解釋以下。 git
一、準備工做:github
(1)在使用org.json以前,咱們應該先從該網址 https://github.com/douglascrockford/JSON-java下載org.json源碼,並將源碼其加入到Eclipse中,便可調用。 json
(2)查看相關的API文檔,訪問:https://github.com/douglascrockford/JSON-java 。 數組
二、org.json的使用:服務器
(1)JSONObject:session
是一個無序的鍵/值對集合。 函數
它的表現形式是一個包裹在花括號的字符串,鍵和值之間使用冒號隔開,鍵值和鍵值之間使用逗號隔開。 工具
內在形式是一個使用get()和opt()方法經過鍵來訪問值,和使用put()方法經過鍵來添加或者替代值的對象。
值能夠是任何這些類型:Boolean,JSONArray,JSONObject,Number和String,或者JOSONObject.NULL對象。
代碼演示以下:
1 public static void jsonObjectTest() { 2 JSONObject jsonobj = new JSONObject("{'name':'xiazdong','age':20}"); 3 String name = jsonobj.getString("name"); 4 int age = jsonobj.getInt("age"); 5 System.out.println("name = " + name + ",age = " + age); 6 }
注:JSONObject有不少optXXX方法,好比optBoolean, optString, optInt...
他們的意思是,若是這個jsonObject有這個屬性,則返回這個屬性,不然返回一個默認值。
(2)JSONArray:
是一個有序的序列值。
它的表現形式是一個包裹在方括號的字符串,值和值之間使用逗號隔開。
內在形式是一個使用get()和opt()方法經過索引來訪問值,和使用put()方法來添加或修改值的對象。
值能夠是任何這些類型:Boolean,JSONArray,JSONObject,Number,和String,或者JSONObject.NULL對象。
代碼演示以下:
1 public static void jsonArrayTest() { 2 JSONArray jsonarray = new JSONArray("[{'name':'xiazdong','age':20},{'name':'xzdong','age':15}]"); 3 for (int i = 0; i < jsonarray.length(); i++) { 4 JSONObject jsonobj = jsonarray.getJSONObject(i); 5 String name = jsonobj.getString("name"); 6 int age = jsonobj.getInt("age"); 7 System.out.println("name = " + name + ",age = " + age); 8 } 9 }
嵌套的JSONObject和JSONArray代碼演示以下:
1 public static void jsonObjectAndArrayTest() { 2 String jsonstring = "{'name':'xiazdong','age':20,'book':['book1','book2']}"; 3 JSONObject jsonobj = new JSONObject(jsonstring); 4 5 String name = jsonobj.getString("name"); 6 System.out.println("name" + ":" + name); 7 8 int age = jsonobj.getInt("age"); 9 System.out.println("age" + ":" + age); 10 11 JSONArray jsonarray = jsonobj.getJSONArray("book"); 12 for (int i = 0; i < jsonarray.length(); i++) { 13 String book = jsonarray.getString(i); 14 System.out.println("book" + i + ":" + book); 15 } 16 }
(3)JSONStringer:
是一個用於快速構造JSON文本的工具
JSONWriter的子類
bject():開始一個對象,即添加{;enObject():結束一個對象,即添加}
array():開始一個數組,即添加[; endArray():結束一個數組,即添加]
key():表示添加一個key;value():表示添加一個value
代碼演示以下:
1 public static void jsonStringerTest() { 2 JSONStringer stringer = new JSONStringer(); 3 stringer.object().key("name").value("xiazdong").key("age").value(20).endObject(); 4 System.out.println(stringer); 5 }
負載的JSON格式寫演示(PrintWriter+JSONStringer能夠寫入JSON文件):
1 public static void jsonStringerTest2() throws FileNotFoundException { 2 JSONStringer jsonStringer = new JSONStringer(); 3 4 JSONObject obj6 = new JSONObject(); 5 obj6.put("title", "book1").put("price", "$11"); 6 7 JSONObject obj3 = new JSONObject(); 8 obj3.put("book", obj6); 9 obj3.put("author", new JSONObject().put("name", "author-1")); 10 11 JSONObject obj5 = new JSONObject(); 12 obj5.put("title", "book2").put("price", "$22"); 13 14 JSONObject obj4 = new JSONObject(); 15 obj4.put("book", obj5); 16 obj4.put("author", new JSONObject().put("name", "author-2")); 17 18 JSONArray obj2 = new JSONArray(); 19 obj2.put(obj3).put(obj4); 20 21 JSONObject obj1 = new JSONObject(); 22 obj1.put("title", "BOOK"); 23 obj1.put("signing", obj2); 24 25 jsonStringer.object().key("session").value(obj1).endObject(); 26 System.out.println(jsonStringer.toString()); 27 28 PrintWriter out = new PrintWriter(new FileOutputStream("1.txt")); 29 out.println(jsonStringer.toString()); 30 out.close(); 31 }
(4)JSONTokener
它和JSONObject和JSONArray的構造函數一塊兒使用,用於解析JSON源字符串
代碼演示以下(JSONObject+JSONTokener可以獲取JSON格式文本對象):
1 public static void JSONTokenerTest() throws FileNotFoundException { 2 JSONObject jsonobj = new JSONObject(new JSONTokener(new FileReader(new File("1.txt")))); 3 System.out.println(jsonobj.getJSONObject("session").getJSONArray("signing").getJSONObject(1).getJSONObject("book").getString("title")); 4 }
注意:在Java中,JSON格式的字符串最好用單引號表示
3、fastjson是一個阿里巴巴開發的Json處理工具包,包括"序列化"和"反序列化"兩部分,它具有以下特徵:
速度最快,測試代表,fastjson具備極快的性能,超越任其餘的Java Json parser,包括自稱最快的JackJson;
功能強大,徹底支持Java Bean、集合、Map、日期、Enum,支持範型,支持自省;
無依賴,可以直接運行在Java SE 5.0以上版本;
支持Android;
開源 (Apache 2.0)
一、Fastjson API入口類是com.alibaba.fastjson.JSON,經常使用的序列化操做均可以在JSON類上的靜態方法直接完成:
public static final Object parse(String text); // 把JSON文本parse爲JSONObject或者JSONArray public static final JSONObject parseObject(String text); // 把JSON文本parse成JSONObject public static final T parseObject(String text, Class clazz); // 把JSON文本parse爲JavaBean public static final JSONArray parseArray(String text); // 把JSON文本parse成JSONArray public static final List parseArray(String text, Class clazz); //把JSON文本parse成JavaBean集合 public static final String toJSONString(Object object); // 將JavaBean序列化爲JSON文本 public static final String toJSONString(Object object, boolean prettyFormat); // 將JavaBean序列化爲帶格式的JSON文本 public static final Object toJSON(Object javaObject); //將JavaBean轉換爲JSONObject或者JSONArray。
二、FastJson解析JSON數據步驟:
(1)服務器端將數據轉換成JSON字符串:
首先服務器端項目要導入阿里巴巴的fastjson的jar包至builtPath路徑下,以下圖:
而後將數據轉爲json字符串,核心函數是:
public static String createJsonString(Object value) { String alibabaJson = JSON.toJSONString(value); return alibabaJson; }
(2)客戶端將JSON字符串 轉換爲 相應的Java Bean
首先客戶端也是須要導入fastjson兩個jar包
public class HttpUtil { public static String getJsonContent(String urlStr) { try {// 獲取HttpURLConnection鏈接對象 URL url = new URL(urlStr); HttpURLConnection httpConn = (HttpURLConnection) url .openConnection(); // 設置鏈接屬性 httpConn.setConnectTimeout(3000); httpConn.setDoInput(true); httpConn.setRequestMethod("GET"); // 獲取相應碼 int respCode = httpConn.getResponseCode(); if (respCode == 200) { return ConvertStream2Json(httpConn.getInputStream()); } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return ""; } private static String ConvertStream2Json(InputStream inputStream) { String jsonStr = ""; // ByteArrayOutputStream至關於內存輸出流 ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; // 將輸入流轉移到內存輸出流中 try { while ((len = inputStream.read(buffer, 0, buffer.length)) != -1) { out.write(buffer, 0, len); } // 將內存流轉換爲字符串 jsonStr = new String(out.toByteArray()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return jsonStr; } }
(2)客戶端得到Java Bean
首先咱們定義兩個Bean類 User 和 Group:
工程結構圖,以下:
User:
public class User { private Long id; private String name; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
Group:
public class Group { private Long id; private String name; private List<User> users = new ArrayList<User>(); public Long getId() {
return id;
} public void setId(Long id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public List<User> getUsers() {
return users;
} public void setUsers(List<User> users) {
this.users = users;
} }
測試代碼FastJsonTest,以下:
package com.himi.fastjson; import java.util.List; import com.alibaba.fastjson.JSON; public class FastJsonTest { public static void main(String[] args) { Group group = new Group(); group.setId(0L); group.setName("admin"); User guestUser = new User(); guestUser.setId(2L); guestUser.setName("guest"); User rootUser = new User(); rootUser.setId(3L); rootUser.setName("root"); group.getUsers().add(guestUser); group.getUsers().add(rootUser); String jsonString = JSON.toJSONString(group); System.out.println(jsonString); System.out.println("--------------------"); Group group2 = JSON.parseObject(jsonString, Group.class); List<User> lists = group2.getUsers(); for(int i=0; i<lists.size(); i++) { User user = (User)lists.get(i); System.out.println("ID:"+user.getId()+" Name:"+user.getName()); } } }
代碼運行效果,以下:
3、Gson是一個能把Java對象轉化成JSON表現形式的一個庫。而且他也能把一個JSON 字符串轉換成等價的Java對象。Gson 是Google 開源出來的一個開源項目, 目前代碼託管在github上。聽說他很吊,能操做任何的java對象,甚至是沒有源碼的已經存在的Java對象。
新建一個JAVA工程爲:GsonDemo,同時導入gson-2.3.1.jar包,以下:
一、將數組 轉化爲 JSON字符串:
在com.himi.gson,新建一個ArrayToJson,以下:
1 package com.himi.gson; 2 3 import com.google.gson.Gson; 4 5 public class ArrayToJson { 6 7 public static void main(String[] args) { 8 // TODO Auto-generated method stub 9 int numbers[] = {1,2,3,4,5,6,7}; 10 String[] days = {"Sun","Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; 11 12 Gson gson = new Gson(); 13 String numbersJson = gson.toJson(numbers); 14 String daysJson = gson.toJson(days); 15 System.out.println("numbers數組轉化爲JSON數據:"+numbersJson); 16 System.out.println("days數組轉化爲JSON數據:"+daysJson); 17 18 System.out.println(""); 19 System.out.println("-------將JSON字符串轉化爲字符串數組-------"); 20 String[] weekdays = gson.fromJson(daysJson, String[].class); 21 for(int i=0; i<weekdays.length; i++) { 22 if (i == weekdays.length - 1) { 23 System.out.print(weekdays[i]); 24 } else { 25 System.out.print(weekdays[i] + ","); 26 } 27 } 28 29 System.out.println(""); 30 System.out.println("-------將多維int數組轉化爲Json-------"); 31 int[][] data = {{1, 2, 3}, {3, 4, 5}, {4, 5, 6}}; 32 String json = gson.toJson(data); 33 System.out.println("Data = " + json); 34 35 36 System.out.println("-------將JSON字符串組轉化爲多維int數組-------"); 37 int[][] dataMap = gson.fromJson(json, int[][].class); 38 for (int i = 0; i < data.length; i++) { 39 for (int j = 0; j < data[i].length; j++) { 40 System.out.print(data[i][j] + " "); 41 } 42 System.out.println(""); 43 } 44 } 45 46 }
運行效果,以下:
二、將JAVA集合 轉化爲 JSON字符串:
新建一個包爲com.himi.gson.bean,在內部新建一個類Student,以下:
1 package com.himi.gson.bean; 2 3 import java.util.Date; 4 5 public class Student { 6 private String name; 7 private String address; 8 private Date dateOfbirth; 9 10 public Student() { 11 12 } 13 public Student(String name, String address, Date dateOfbirth) { 14 super(); 15 this.name = name; 16 this.address = address; 17 this.dateOfbirth = dateOfbirth; 18 } 19 public String getName() { 20 return name; 21 } 22 public void setName(String name) { 23 this.name = name; 24 } 25 public String getAddress() { 26 return address; 27 } 28 public void setAddress(String address) { 29 this.address = address; 30 } 31 public Date getDateOfbirth() { 32 return dateOfbirth; 33 } 34 public void setDateOfbirth(Date dateOfbirth) { 35 this.dateOfbirth = dateOfbirth; 36 } 37 38 }
同時在com.himi.gson包下,新建一個類CollectToJson,以下:
1 package com.himi.gson; 2 3 import java.util.ArrayList; 4 import java.util.Date; 5 import java.util.List; 6 import java.lang.reflect.Type; 7 8 import com.google.gson.Gson; 9 import com.google.gson.reflect.TypeToken; 10 import com.himi.gson.bean.Student; 11 12 public class CollectToJson { 13 14 public static void main(String[] args) { 15 Gson gson = new Gson(); 16 17 System.out.println("-----------將List的字符串集合轉化爲JSON字符串-----------"); 18 List<String> names = new ArrayList<String>(); 19 names.add("Alice"); 20 names.add("Bob"); 21 names.add("Carol"); 22 names.add("Mallory"); 23 24 String jsonNames = gson.toJson(names); 25 System.out.println("jsonNames = " + jsonNames); 26 27 System.out.println("-----------將List的Student集合轉化爲JSON字符串-----------"); 28 Student a = new Student("Alice", "Apple St", new Date(2000, 10, 1)); 29 Student b = new Student("Bob", "Banana St", null); 30 Student c = new Student("Carol", "Grape St", new Date(2000, 5, 21)); 31 Student d = new Student("Mallory", "Mango St", null); 32 33 List<Student> students = new ArrayList<Student>(); 34 students.add(a); 35 students.add(b); 36 students.add(c); 37 students.add(d); 38 39 String jsonStudents = gson.toJson(students); 40 System.out.println("jsonStudents = " + jsonStudents); 41 42 System.out.println("-----------將JSON字符串轉化爲一個Student類的集合-----------"); 43 Type type = new TypeToken<List<Student>>() { 44 }.getType(); 45 List<Student> studentList = gson.fromJson(jsonStudents, type); 46 47 for (Student student : studentList) { 48 System.out.println("student.getName() = " + student.getName()+"\n" 49 +"student.getAddress() = "+student.getAddress()+"\n" 50 +"student.getDateOfbirth() = "+student.getDateOfbirth()); 51 System.out.println(""); 52 } 53 54 } 55 56 }
運行效果,以下:
三、將Map 轉化爲 Json字符串:
在com.himi.gson包下,新建一個MapToJson,以下:
package com.himi.gson; import java.lang.reflect.Type; import java.util.HashMap; import java.util.Map; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; public class MapToJson { public static void main(String[] args) { Map<String, String> colours = new HashMap<String, String>(); colours.put("BLACK", "#000000"); colours.put("RED", "#FF0000"); colours.put("GREEN", "#008000"); colours.put("BLUE", "#0000FF"); colours.put("YELLOW", "#FFFF00"); colours.put("WHITE", "#FFFFFF"); System.out.println("將一個Map轉化爲Json字符串"); Gson gson = new Gson(); String json = gson.toJson(colours); System.out.println("json = " + json); System.out.println("---------------------"); System.out.println("將一個Json字符串轉化一個Map"); Type type = new TypeToken<Map<String, String>>() { }.getType(); Map<String, String> map = gson.fromJson(json, type); for (String key : map.keySet()) { System.out.println("map.get = " + map.get(key)); } } }
運行效果,以下:
四、將對象 轉化爲 Json字符串:
在com.himi.gson包下,新建一個類StudentToJson,以下:
1 package com.himi.gson; 2 3 import java.util.Calendar; 4 5 import com.google.gson.Gson; 6 import com.himi.gson.bean.Student; 7 8 public class StudentToJson { 9 10 public static void main(String[] args) { 11 Calendar dob = Calendar.getInstance(); 12 dob.set(2000, 1, 1, 0, 0, 0); 13 Student student = new Student("Duke", "Menlo Park", dob.getTime()); 14 15 Gson gson = new Gson(); 16 String json = gson.toJson(student); 17 System.out.println("json = " + json); 18 19 } 20 21 }
運行效果以下:
五、將Json字符串 轉化爲 對象:
在com.himi.gson包下,新建一個JsonToStudent,以下:
1 package com.himi.gson; 2 3 import com.google.gson.Gson; 4 import com.himi.gson.bean.Student; 5 6 public class JsonToStudent { 7 8 public static void main(String[] args) { 9 String json = "{\"name\":\"Duke\",\"address\":\"Menlo Park\",\"dateOfBirth\":\"Feb 1, 2000 12:00:00 AM\"}"; 10 11 Gson gson = new Gson(); 12 Student student = gson.fromJson(json, Student.class); 13 14 System.out.println("student.getName() = " + student.getName()); 15 System.out.println("student.getAddress() = " + student.getAddress()); 16 System.out.println("student.getDateOfbirth() = " + student.getDateOfbirth()); 17 } 18 }
運行效果,以下: