Android进阶笔记14:3种JSON解析工具(org.json、fastjson、gson)

1、 目前解析json有三种工具:org.json(Java经常使用的解析),fastjson(阿里巴巴工程师开发的),Gson(Google官网出的),其中解析速度最快的是Gsonhtml

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方法,好比optBooleanoptStringoptInt... 

他们的意思是,若是这个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包

  • 客户端获取JSON字符串
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类 UserGroup

工程结构图,以下:

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 }

运行效果,以下:

相关文章
相关标签/搜索