什麼是JSON:
JSON即JavaScript Object Natation, 它是一種輕量級的數據交換格式, 與XML一樣, 是廣泛被采用的客戶端和服務端交互的解決方案.
JSON對象:
JSON中對象(Object)以"{"開始, 以"}"結束. 對象中的每一個item都是一個key-value對, 表現為"key:value"的形式, key-value對之間使用逗號分隔. 如:{"name":"coolxing", "age"=24, "male":true, "address":{"street":"huiLongGuan", "city":"beijing", "country":"china"}}. JSON對象的key只能是string類型的, 而value可以是string, number, false, true, null, Object對象甚至是array數組, 也就是說可以存在嵌套的情況.
JSON數組:
JSON數組(array)以"["開始, 以"]"結束, 數組中的每一個元素可以是string, number, false, true, null, Object對象甚至是array數組, 數組間的元素使用逗號分隔. 如["coolxing", 24, {"street":"huiLongGuan", "city":"beijing", "country":"china"}].
JSON數據的解析:
解析JSON數據, 首先需要明確待解析的是JSON Object還是JSON array, 然後需要確定采用哪種解析技術. android平台上一般有2種解析技術可供選擇:android內置的org.json包和google的開源gson庫. 以下將分別采用這兩種技術解析JSON對象和JSON數組.
1. 采用android內置的org.json包解析JSON對象. 假設待解析的JSON數據為json = "{\"name\":\"coolxing\", \"age\"=24, \"male\":true, \"address\":{\"street\":\"huiLongGuan\", \"city\":\"beijing\", \"country\":\"china\"}}", 其中\用於轉義表達式中的雙引號. 首先定義2個JavaBean:
[java]
package text.com.bean;
public class Address {
private String street;
private String city;
private String country;
public Address() {
super();
}
public Address(String street, String city, String country) {
super();
this.street = street;
this.city = city;
this.country = country;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
@Override
public String toString() {
return "Address [street=" + street + ", city=" + city + ", country="
+ country + "]";
}
}
[java]
package text.com.bean;
public class Person {
private String name;
private int age;
private boolean male;
private Address address;
public Person() {
super();
}
public Person(String name, int age, boolean male, Address address) {
super();
this.name = name;
this.age = age;
this.male = male;
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean isMale() {
return male;
}
public void setMale(boolean male) {
this.male = male;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + ", male=" + male
+ ", address=" + address + "]";
}
}
首先使用方法一解析代碼如下:
[java]
JSONObject jsonObject = new JSONObject(json);
String name = jsonObject.getString("name");
int age = jsonObject.getInt("age");
boolean male = jsonObject.getBoolean("male");
JSONObject addressJSON = jsonObject.getJSONObject("address");
String street = addressJSON.getString("street");
String city = addressJSON.getString("city");
String country = addressJSON.getString("country");
Address address = new Address(street, city, country);
Person person = new Person(name, age, male, address);
System.out.println(person);
LogCat的輸出為Person [name=coolxing, age=24, male=true, address=Address [street=huiLongGuan, city=beijing, country=china]], 說明已經正確解析了JSON對象.
2. 采用gson庫解析JSON對象. 假設帶解析的JSON數據是json = "{\"name\":\"coolxing\", \"age\"=24, \"male\":true, \"address\":{\"street\":\"huiLongGuan\", \"city\":\"beijing\", \"country\":\"china\"}}", 首先需要到http://code.google.com/p/google-gson/下載jar包, 並將其添加到項目中. 具體的解析代碼如下:
[java]
Gson gson = new Gson();
Person person = gson.fromJson(json, Person.class);
System.out.println(person);
LogCat的輸出為Person [name=coolxing, age=24, male=true, address=Address [street=huiLongGuan, city=beijing, country=china]], 說明已經正確解析了JSON對象, 是不是很簡單?
3. 采用android內置的org.json包解析JSON數組. 假設待解析的JSON數據為json = "[{\"name\":\"coolxing\", \"age\"=24, \"male\":true, \"address\":{\"street\":\"huiLongGuan\", \"city\":\"beijing\", \"country\":\"china\"}}, {\"name\":\"min\", \"age\"=20, \"male\":false, \"address\":{\"street\":\"heiShiJiao\", \"city\":\"daLian\", \"country\":\"china\"}}]", 解析代碼如下:
[java]
List<Person> persons = new ArrayList<Person>();
JSONArray jsonArray = new JSONArray(json);
for(int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String name = jsonObject.getString("name");
int age = jsonObject.getInt("age");
boolean male = jsonObject.getBoolean("male");
JSONObject addressJSON = jsonObject.getJSONObject("address");
String street = addressJSON.getString("street");
String city = addressJSON.getString("city");
String country = addressJSON.getString("country");
Address address = new Address(street, city, country);
Person person = new Person(name, age, male, address);
persons.add(person);
}
System.out.println(persons);
LogCat的輸出為[Person [name=coolxing, age=24, male=true, address=Address [street=huiLongGuan, city=beijing, country=china]], Person [name=min, age=20, male=false, address=Address [street=heiShiJiao, city=daLian, country=china]]], 說明已經正確解析了JSON數組.
4. 采用gson庫解析JSON數組. 待解析的JSON數據同上, 具體代碼為:
[java]
Gson gson = new Gson();
Type listType = new TypeToken<List<Person>>(){}.getType();
List<Person> persons = gson.fromJson(json, listType);
LogCat的輸出為[Person [name=coolxing, age=24, male=true, address=Address [street=huiLongGuan, city=beijing, country=china]], Person [name=min, age=20, male=false, address=Address [street=heiShiJiao, city=daLian, country=china]]], 說明已經正確解析了JSON數組.
new TypeToken<List<Person>>(){}.getType(); 這句代碼表示創建一個TypeToken的匿名子類對象, 並調用對象的getType()方法.
org.json包和gson庫還有很多其他有用的API, 需要的時候可查看文檔. 比如有的時候需要通過java對象或java集合和數組生成json數據上傳給服務器, 當然你可以自我構造json字符串, 但會很麻煩. 這個時候就可以使用其中的有關API, 方便的完成這項工作.
測試用例:
[java]
package text.com;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.util.List;
import text.com.bean.Address;
import text.com.bean.Person;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class JsonTest {
String jsonString = "";
public static void main(String[] args) {
// Person p1 = new Person("zhangsan", 12, true, new Address("北京", "海澱區",
// "30號"));
// Person p2 = new Person("zhangsan", 12, true, new Address("北京", "海澱區",
// "30號"));
// Person p3 = new Person("zhangsan", 12, true, new Address("北京", "海澱區",
// "30號"));
// List<Person> list = new ArrayList<Person>();
// list.add(p1);
// list.add(p2);
// list.add(p3);
// Gson gson = new Gson();
// Type typeOfT = new TypeToken<List<Person>>(){}.getType();
// String json = gson.toJson(list, typeOfT);
// System.out.println("json:"+json);
// String str = readTxtFile("D:\\cjjworkspace\\Test\\json.txt");
// System.out.println("文件內容:" + str);
Gson gson = new Gson();
// Type typeOfT = new TypeToken<List<Person>>(){}.getType();
// List<Person> personList = gson.fromJson(str, typeOfT);
Person p1 = new Person("zhangsan", 12, true, new Address("北京", "海澱區", "30號"));
Type typeOfT = new TypeToken<Person>(){}.getType();
String str = gson.toJson(p1, typeOfT);
System.out.println(str);
}
public static String readTxtFile(String filePath) {
String encoding = "utf-8";
StringBuilder sb = new StringBuilder();
try {
File file = new File(filePath);
if (file.isFile() && file.exists()) { // 判斷文件是否存在
InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);// 考慮到編碼格式
BufferedReader bufferedReader = new BufferedReader(read);
String str = "";
while ((str = bufferedReader.readLine()) != null) {
sb.append(str);
}
read.close();
return sb.toString();
} else {
System.out.println("找不到指定的文件");
return null;
}
} catch (Exception e) {
System.out.println("讀取文件內容出錯");
e.printStackTrace();
}
return sb.toString();
}
}
附帶:gson-2.2.4.jar
gson-2.2.4-javadoc.jar
gson-2.2.4-sources.jar