什么是JSON:
JavaScript Object Notation是一种轻量级的数据交换格式
与xml差异:
+ JSON相对于XML来讲,数据的体积小
+ JSON与JavaScript的交互更加方便
+ JSON的速度要远远快于XML
+ JSON对数据的描述性比XML较差
JSON构成:
(1) 对象:无序的“‘名称/值’对”集合。一个对象以“{”开始,以“}”结束。每个“名称”后跟一个“:”,“‘名称/值’对”之间使用“,”分隔。
(2) 数组:值(value)的有序集合。一个数组以“[”开始,“]”结束。值之间使用“,”分隔。其中,值(value)可以是双引号括起来的字符串(String)、数值(number)、true、false、null、对象(object)或者数组(array)。这些结构可以嵌套。
Gson方法:
数组<--->Json
int[] numbers = {1, 1, 2, 3, 5, 8, 13};
String[] days = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
Gson gson = new Gson();
String numbersJson = gson.toJson(numbers);
String daysJson = gson.toJson(days);
System.out.println("numbersJson = " + numbersJson);//numbersJson = [1,1,2,3,5,8,13]
System.out.println("daysJson = " + daysJson);//daysJson = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]
int[] fibonacci = gson.fromJson(numbersJson, int[].class);
String[] weekDays = gson.fromJson(daysJson, String[].class);
集合<--->Json
List<String> names = new ArrayList<String>();
names.add("Alice");
names.add("Bob");
names.add("Carol");
names.add("Mallory");
Gson gson = new Gson();
String jsonNames = gson.toJson(names);//jsonNames = ["Alice","Bob","Carol","Mallory"]
Student a = new Student("Alice", "Apple St", new Date(2000, 10, 1));
Student b = new Student("Bob", "Banana St", null);
Student c = new Student("Carol", "Grape St", new Date(2000, 5, 21));
Student d = new Student("Mallory", "Mango St", null);
List<Student> students = new ArrayList<Student>();
students.add(a);
students.add(b);
students.add(c);
students.add(d);
gson = new Gson();
String jsonStudents = gson.toJson(students);//[{"name":"Alice","address":"Apple St","dateOfBirth":"Nov 1, 3900 12:00:00 AM"},{"name":"Bob","address":"Banana St"},{"name":"Carol","address":"Grape St","dateOfBirth":"Jun 21, 3900 12:00:00 AM"},{"name":"Mallory","address":"Mango St"}]
Type type = new TypeToken<List<Student>>(){}.getType();
List<Student> studentList = gson.fromJson(jsonStudents, type);
Map<--->Json
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");
Gson gson = new Gson();
String json = gson.toJson(colours);
//{"WHITE":"#FFFFFF","BLUE":"#0000FF","YELLOW":"#FFFF00","GREEN":"#008000","BLACK":"#000000","RED":"#FF0000"}
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
Student student = new Student("Duke", "Menlo Park", dob.getTime());
Gson gson = new Gson();
String json = gson.toJson(student);
//{"name":"Duke","address":"Menlo Park","dateOfBirth":"Feb 1, 2000 12:00:00 AM"}
Gson gson = new Gson();
Student student = gson.fromJson(json, Student.class);
嵌套解析
package test0328;
import java.util.Arrays;
public class Person {
/*
* {
"phone" : ["112233", "445566"], // 数组
"name" : "android", // 字符串
"age" : 5, // 数值
"address" : { "country" : "china", "province" : "ShangHai" }, // 对象
"married" : false // 布尔值
},
*
*/
private String[] phone;
/**
* @return the address
*/
public Address getAddress() {
return address;
}
/**
* @param address
* the address to set
*/
public void setAddress(Address address) {
this.address = address;
}
private String name;
private int age;
private Address address = null;
private boolean married;
/**
* @return the phone
*/
public String[] getPhone() {
return phone;
}
/**
* @param phone
* the phone to set
*/
public void setPhone(String[] phone) {
this.phone = phone;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Person [phone=" + Arrays.toString(phone) + ", name=" + name
+ ", age=" + age + ", address=" + address + ", married="
+ married + "]";
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name
* the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the age
*/
public int getAge() {
return age;
}
/**
* @param age
* the age to set
*/
public void setAge(int age) {
this.age = age;
}
/**
* @return the married
*/
public boolean isMarried() {
return married;
}
/**
* @param married
* the married to set
*/
public void setMarried(boolean married) {
this.married = married;
}
}
package test0328;
public class Address {
// "address" : { "country" : "china", "province" : "ShangHai" }, // 对象
private String country;
private String province;
/**
* @return the country
*/
public String getCountry() {
return country;
}
/**
* @param country
* the country to set
*/
public void setCountry(String country) {
this.country = country;
}
/**
* @return the province
*/
public String getProvince() {
return province;
}
/**
* @param province
* the province to set
*/
public void setProvince(String province) {
this.province = province;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Address [country=" + country + ", province=" + province + "]";
}
}
package test0328;
import java.io.StringReader;
import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;
public class Json {
/*
[{
"phone" : ["112233", "445566"], // 数组
"name" : "android", // 字符串
"age" : 5, // 数值
"address" : { "country" : "PRC", "province" : "ShangHai" }, // 对象
"married" : false // 布尔值
},
{
"phone" : ["778899", "224466"], // 数组
"name" : "Linux", // 字符串
"age" : 15, // 数值
"address" : { "country" : "USA", "province" : "NY" }, // 对象
"married" : true // 布尔值
}]
*/
private static final String Json = "[{\"phone\" : [\"112233\", \"445566\"], \"name\" : \"android\", \"age\" : 5, \"address\" : { \"country\" : \"china\", \"province\" : \"ShangHai\" }, \"married\" : false},{\"phone\" : [\"778899\", \"224466\"], \"name\" : \"linux\",\"age\" : 15, \"address\" : { \"country\" : \"USA\", \"province\" : \"NY\" },\"married\" : true }]";
private static Gson gson = new Gson();
public static void main(String[] args) throws Exception {
JsonReader reader = new JsonReader(new StringReader(Json));
reader.beginArray();//开始数组
while(reader.hasNext()){//循环
reader.beginObject();//开始对象
Person person = new Person();
while(reader.hasNext()){//循环
String tagName = reader.nextName();
if("phone".equals(tagName)){
reader.beginArray();
String[] phones = new String[2];
phones[0] = reader.nextString();
phones[1] = reader.nextString();
person.setPhone(phones);
reader.endArray();
}else if("name".equals(tagName)){
person.setName(reader.nextString());
}else if("age".equals(tagName)){
person.setAge(reader.nextInt());
}else if("address".equals(tagName)){
reader.beginObject();
Address address = new Address();
while(reader.hasNext()){
int i = 0;
String tagName2 = reader.nextName();
if("country".equals(tagName2)){
address.setCountry(reader.nextString());
}else{
address.setProvince(reader.nextString());
}
}
person.setAddress(address);
reader.endObject();
}else if("married".equals(tagName)){
person.setMarried(reader.nextBoolean());
}
}
reader.endObject();
System.out.println(person);
}
reader.endArray();
}
public static int[] intsfromJson(String json){
return gson.fromJson(json, int[].class);
}
public static String[] stringsfromJson(String json){
return gson.fromJson(json, String[].class);
}
}