簡書著作權歸作者所有,任何形式的轉載都請聯系作者獲得授權并注明出處。
依賴
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.6.2</version>
</dependency>
? ? ? ?關于這個話題,需要注意的細節還是有一些的,這里只是結合自身需要整理了最基本的用法。如果想要了解更多細節性的問題,可以參考 http://www.lxweimin.com/p/e740196225a4 (怪盜kidou)系列文章。
一、Json 字符串轉換為 Java 對象
? ? ? ?假設我們有如下的 json 字符串:
{
"id": "001",
"name": "zhangsan",
"score": 90,
"hobbies": [
"soccer",
"chess"
]
}
? ? ? ?若要將一個 json 字符串轉換為一個 java 對象,我們首先需要編寫與該 json 字符串相應的 java 類,如下:
public class Student {
private String id;
private String name;
private int score;
private List<String> hobbies = new ArrayList<>();
// getter and setter methods are omitted here.
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", score=" + score + ", hobbies=" + hobbies + "]";
}
}
? ? ? ?將以上 json 字符串轉換為 Student 對象的方式很簡單,代碼如下:
public class GsonDemo {
public static void main(String[] args) {
String jsonStr = "{\"id\": \"001\", \"name\": \"zhangsan\", \"score\": 90, \"hobbies\": [\"soccer\", \"chess\"]}";
Gson gson = new Gson();
Student student = gson.fromJson(jsonStr, Student.class);
System.out.println(student);
}
}
? ? ? ?代碼執行結果如下:
Student [id=001, name=zhangsan, score=90, hobbies=[soccer, chess]]
存在的問題
? ? ? ?對于上面的實現方式,我們發現,json 字符串中的各個 key(鍵) 和定義的 Student 類中的各個屬性名都是對應相同的,如 json 字符串中有 id,name,score 和 hobbies 四個 key,同時在 Student 類中定義了四個屬性,名稱也是 id,name,score 和 hobbies。這種情況下,以上的代碼執行的結果完全符合我們的預期。但如果 Student 類中定義的屬性名稱分別是 id,name,marks 和 hobbies,即 json 字符串中的 key 和 Student 類中的屬性名不是完全對應相同的情況下,以上代碼的執行結果卻是
Student [id=001, name=zhangsan, marks=0, hobbies=[soccer, chess]]
? ? ?我們發現 marks 屬性沒有被轉換。
解決方案
? ? ? ?對于上面存在的問題,我們的解決方式是使用注解。現在我們將給 Student 類的 marks 屬性加上注解,代碼如下:
public class Student {
private String id;
private String name;
@SerializedName("score")
private int marks;
private List<String> hobbies = new ArrayList<>();
// getter and setter methods are omitted here.
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", marks=" + marks + ", hobbies=" + hobbies + "]";
}
}
? ? ? ?我們再次執行客戶端代碼,結果如下:
Student [id=001, name=zhangsan, marks=90, hobbies=[soccer, chess]]
? ? ? ?發現在 Student 類中給 marks 屬性加上注解之后,該屬性可以被正常轉換了。
二、Java 對象轉換為 Json 字符串
? ? ? ?將 Java 對象轉換為 Json 字符串相對來說簡單一些,代碼如下:
? ? ? ?Student 類:
public class Student {
private String id;
private String name;
@SerializedName("score")
private int marks;
private List<String> hobbies = new ArrayList<>();
public Student(String id, String name, int marks, List<String> hobbies) {
this.id = id;
this.name = name;
this.marks = marks;
this.hobbies = hobbies;
}
// getter and setter methods are omitted here.
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", marks=" + marks + ", hobbies=" + hobbies + "]";
}
}
? ? ? ?客戶端代碼:
public class GsonDemo {
public static void main(String[] args) {
List<String> hobbies = Arrays.asList("soccer", "chess");
Student student = new Student("001", "zhangsan", 90, hobbies);
Gson gson = new Gson();
String jsonStr = gson.toJson(student);
System.out.println(jsonStr);
}
}
? ? ? ?執行結果如下:
{"id":"001","name":"zhangsan","score":90,"hobbies":["soccer","chess"]}
? ? ? ?注意:我們發現,Student 類中的屬性 marks 在轉換為 json 字符串后,對應的是 json 字符串中的 score 。也就是說 @SerializedName 注解在將 java 對象轉換為 json 字符串的過程中也是起作用的。
額外注意點
1、從文件中讀取 json 字符串并轉換為 java 對象
? ? ? ?json 文件內容如下:
{
"id": "001",
"name": "zhangsan",
"score": 90,
"hobbies": [
"soccer",
"chess"
]
}
? ? ? ?客戶端代碼如下:
public class GsonDemo {
public static void main(String[] args) throws Exception {
Gson gson = new Gson();
Student student = gson.fromJson(new FileReader("file.json"), Student.class);
System.out.println(student);
}
}
2、格式化輸出 json 字符串
? ? ? ?只需要將
Gson gson = new Gson();
? ? ? ?改為
Gson gson = new GsonBuilder().setPrettyPrinting().create();
? ? ? ?json 字符串輸出效果如下:
{
"id": "001",
"name": "zhangsan",
"score": 90,
"hobbies": [
"soccer",
"chess"
]
}
上一篇:java 解析 xml 文件實例
下一篇:使用 JSONObject 和 JSONArray 創建 json 字符串