Google Gson使用簡介
阿新 • • 發佈:2019-01-23
轉載:http://www.cnblogs.com/haippy/archive/2012/05/20/2509329.html
如何將陣列轉化為 json 串?
下面的例子中我們示例如何將一個數據轉換成 json 串,並使用 Gson.toJson()
方法將陣列序列化為 JSON,以及Gson.fromJson()
方法將 JSON 串反序列化為 java 陣列。
以下是輸出結果:import com.google.gson.Gson; public class ArrayToJson { public static void main(String[] args) { int[] numbers = {1, 1, 2, 3, 5, 8, 13}; String[] days = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; // // Create a new instance of Gson // Gson gson = new Gson(); // // Convert numbers array into JSON string. // String numbersJson = gson.toJson(numbers); // // Convert strings array into JSON string // String daysJson = gson.toJson(days); System.out.println("numbersJson = " + numbersJson); System.out.println("daysJson = " + daysJson); // // Convert from JSON string to a primitive array of int. // int[] fibonacci = gson.fromJson(numbersJson, int[].class); for (int i = 0; i < fibonacci.length; i++) { System.out.print(fibonacci[i] + " "); } System.out.println(""); // // Convert from JSON string to a string array. // String[] weekDays = gson.fromJson(daysJson, String[].class); for (int i = 0; i < weekDays.length; i++) { System.out.print(weekDays[i] + " "); } System.out.println(""); // // Converting multidimensional array into JSON // int[][] data = {{1, 2, 3}, {3, 4, 5}, {4, 5, 6}}; String json = gson.toJson(data); System.out.println("Data = " + json); // // Convert JSON string into multidimensional array of int. // int[][] dataMap = gson.fromJson(json, int[][].class); for (int i = 0; i < data.length; i++) { for (int j = 0; j < data[i].length; j++) { System.out.print(data[i][j] + " "); } System.out.println(""); } } }
numbersJson = [1,1,2,3,5,8,13]
daysJson = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]
1 1 2 3 5 8 13
Sun Mon Tue Wed Thu Fri Sat
Data = [[1,2,3],[3,4,5],[4,5,6]]
1 2 3
3 4 5
如何將集合轉化為 json 串?
下面的例子中我們示例如何將Java集合轉換為符合 json 規則的字串。
import java.util.Date; public class Student { private String name; private String address; private Date dateOfBirth; public Student() { } public Student(String name, String address, Date dateOfBirth) { this.name = name; this.address = address; this.dateOfBirth = dateOfBirth; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Date getDateOfBirth() { return dateOfBirth; } public void setDateOfBirth(Date dateOfBirth) { this.dateOfBirth = dateOfBirth; } }
import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Date; import java.util.List; public class CollectionToJson { public static void main(String[] args) { // // Converts a collection of string object into JSON string. // 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); System.out.println("jsonNames = " + jsonNames); // // Converts a collection Student object into JSON string // 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); System.out.println("jsonStudents = " + jsonStudents); // // Converts JSON string into a collection of Student object. // Type type = new TypeToken<List<Student>>(){}.getType(); List<Student> studentList = gson.fromJson(jsonStudents, type); for (Student student : studentList) { System.out.println("student.getName() = " + student.getName()); } } }
以下是輸出結果:
jsonNames = ["Alice","Bob","Carol","Mallory"]
jsonStudents = [{"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"}]
student.getName() = Alice
student.getName() = Bob
student.getName() = Carol
student.getName() = Mallory
如何將Map轉化為 json 串?
下面的例子中我們示例如何將java.util.Map
轉化成 json 串,然後再將 json 串轉換為java.util.Map
。
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
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");
//
// Convert a Map into JSON string.
//
Gson gson = new Gson();
String json = gson.toJson(colours);
System.out.println("json = " + json);
//
// Convert JSON string back to 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 = {"WHITE":"#FFFFFF","BLUE":"#0000FF","YELLOW":"#FFFF00","GREEN":"#008000","BLACK":"#000000","RED":"#FF0000"}
map.get = #FFFFFF
map.get = #0000FF
map.get = #FFFF00
map.get = #008000
map.get = #000000
map.get = #FF0000
如何將物件轉換為 json 串?
下面的例子中我們示例如何將一個 Student 物件轉換成 json 串,實際操作中我們也可以將任意的 Java 類轉換為 json 串,並且實施起來也非常簡單,你僅僅需要建立一個 Gson 例項,然後傳遞將被轉化為 json 串的物件,並呼叫該例項的 toJson 方法即可。
import com.google.gson.Gson;
import java.util.Calendar;
public class StudentToJson {
public static void main(String[] args) {
Calendar dob = Calendar.getInstance();
dob.set(2000, 1, 1, 0, 0, 0);
Student student = new Student("Duke", "Menlo Park", dob.getTime());
Gson gson = new Gson();
String json = gson.toJson(student);
System.out.println("json = " + json);
}
}
import java.util.Date;
public class Student {
private String name;
private String address;
private Date dateOfBirth;
public Student() {
}
public Student(String name, String address, Date dateOfBirth) {
this.name = name;
this.address = address;
this.dateOfBirth = dateOfBirth;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
}
以下是輸出結果:json = {"name":"Duke","address":"Menlo Park","dateOfBirth":"Feb 1, 2000 12:00:00 AM"}
如何將 json 串轉換為物件?
下面的例子中我們示例如何 json 串轉化成 Java物件。
import com.google.gson.Gson;
public class JsonToStudent {
public static void main(String[] args) {
String json = "{\"name\":\"Duke\",\"address\":\"Menlo Park\",\"dateOfBirth\":\"Feb 1, 2000 12:00:00 AM\"}";
Gson gson = new Gson();
Student student = gson.fromJson(json, Student.class);
System.out.println("student.getName() = " + student.getName());
System.out.println("student.getAddress() = " + student.getAddress());
System.out.println("student.getDateOfBirth() = " + student.getDateOfBirth());
}
}
以下是輸出結果:
student.getName() = Duke
student.getAddress() = Menlo Park
student.getDateOfBirth() = Tue Feb 01 00:00:00 CST 2000
如何處理物件的欄位?
下面的例子中我們示例如何利用Gson處理一個物件的某一欄位。
import com.google.gson.Gson;
import java.util.Calendar;
public class GsonFieldExample {
public static void main(String[] args) {
Calendar dob = Calendar.getInstance();
dob.set(1980, 10, 11);
People people = new People("John", "350 Banana St.", dob.getTime());
people.setSecret("This is a secret!");
Gson gson = new Gson();
String json = gson.toJson(people);
System.out.println("json = " + json);
}
}
import java.util.Date;
public class People {
private String name;
private String address;
private Date dateOfBirth;
private Integer age;
private transient String secret;
public People(String name, String address, Date dateOfBirth) {
this.name = name;
this.address = address;
this.dateOfBirth = dateOfBirth;
}
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
}
以下是輸出結果:
json = {"name":"John","address":"350 Banana St.","dateOfBirth":"Nov 11, 1980 8:47:04 AM"}