簡書著作權歸作者所有,任何形式的轉載都請聯系作者獲得授權并注明出處。
依賴
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20160810</version>
</dependency>
? ? ? ?一、應用場景
? ? ? ?在編寫 java 代碼時,很多時候我們需要創建一個 json 字符串。比如在使用 java 代碼請求一個服務時,我們需要在 java 代碼中傳入一些參數,如 url 等,這樣的情況下,請求接口都會要求我們傳入一個 json 類型的參數。
? ? ? ?此時,如果直接使用字符串構造 json 對象也是可以的,如下面這樣:
String jsonStr = "{\"name\":\"bubble\",\"age\":100,\"male\":true}";
? ? ? ?但這樣寫很不優雅,且會因為字符串中的轉義字符很多,容易混亂,甚至當 json 字符串很長時就很難保證所構造的 json 字符串是否正確了。
? ? ? ?二、解決方法
? ? ? ?對于上面描述的使用場景,我們可以使用 JSONObject 和 JSONArray 來構造 json 字符串。下面通過幾個簡單的例子來展示它們的用法。
? ? ? ?1、當 json 中沒有涉及數組時
public class Main {
public static void main(String[] args) {
JSONObject student = new JSONObject();
student.put("name", "bubble");
student.put("age", 100);
student.put("male", true);
System.out.println(student.toString());
}
}
? ? ? ?通過執行上述代碼,可以看到構造的 json 字符串為:
{"name":"bubble","age":100,"male":true}
? ? ? ?2、當 json 中涉及到數組時
public class Main {
public static void main(String[] args) {
JSONObject student1 = new JSONObject();
student1.put("name", "zhangsan");
student1.put("age", 15);
JSONObject student2 = new JSONObject();
student2.put("name", "lisi");
student2.put("age", 16);
JSONArray students = new JSONArray();
students.put(student1);
students.put(student2);
JSONObject classRoom = new JSONObject();
classRoom.put("students", students);
System.out.println(classRoom);
}
}
? ? ? ?通過執行上述代碼,可以看到構造的 json 字符串為:
{"students":[{"name":"zhangsan","age":15},{"name":"lisi","age":16}]}
? ? ? ?通過這兩個例子應該知道如何使用 JSONObject 和 JSONArray 來構造 json 字符串了。