📅  最后修改于: 2023-12-03 15:28:06.405000             🧑  作者: Mango
org.json
是一个 Java 编写的开源 JSON 解析库。它提供了从 JSON 字符串到 JSON 对象及其它 Java 原生数据类型之间的互相转换的功能。org.json
在 Java EE 或者 Android 开发中广泛应用,成为了 Java 开发中的标准 JSON 解析库之一。
import org.json.JSONArray;
import org.json.JSONObject;
public class JsonTest {
public static void main(String[] args) {
String jsonStr = "{\"name\":\"Tom\",\"age\":20,\"isMarried\":false,\"hobbies\":[\"reading\",\"swimming\"]}";
// 将 JSON 字符串转换成 JSON 对象
JSONObject jsonObj = new JSONObject(jsonStr);
// 从 JSON 对象中获取指定 key 的 value
String name = jsonObj.getString("name");
int age = jsonObj.getInt("age");
boolean isMarried = jsonObj.getBoolean("isMarried");
// 从 JSON 对象中获取 JSON 数组并遍历
JSONArray hobbiesArray = jsonObj.getJSONArray("hobbies");
for (int i = 0; i < hobbiesArray.length(); i++) {
System.out.println(hobbiesArray.getString(i));
}
// 将 Java 对象转换成 JSON 对象
JSONObject personObj = new JSONObject();
personObj.put("name", "Jack");
personObj.put("age", 22);
personObj.put("isMarried", true);
JSONArray hobbiesArr = new JSONArray();
hobbiesArr.put("playing basketball");
hobbiesArr.put("listening to music");
personObj.put("hobbies", hobbiesArr);
// 将 JSON 对象转换成 JSON 字符串
String personStr = personObj.toString();
System.out.println(personStr);
}
}
以下是一个使用 org.json
库对 JSON 数据进行解析的完整示例。
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import org.json.JSONArray;
import org.json.JSONObject;
public class JsonTest {
public static void main(String[] args) {
String json = "";
try {
// 从 URL 中获取 JSON 数据
URL url = new URL("https://jsonplaceholder.typicode.com/todos");
URLConnection conn = url.openConnection();
InputStream in = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = null;
while ((line = reader.readLine()) != null) {
json += line;
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}
// 将 JSON 字符串转换成 JSON 数组,遍历其中的 JSON 对象并获取指定 key 的 value
JSONArray todos = new JSONArray(json);
for (int i = 0; i < todos.length(); i++) {
JSONObject todo = todos.getJSONObject(i);
int id = todo.getInt("id");
int userId = todo.getInt("userId");
String title = todo.getString("title");
boolean completed = todo.getBoolean("completed");
System.out.println("id: " + id + ", userId: " + userId + ", title: " + title + ", completed: " + completed);
}
}
}
org.json
是一个简单易用的 JSON 解析库,适用于轻量级的 JSON 数据解析。它的性能稳定,使用方便,不依赖于其它大型框架或库,因此在 Java EE 或 Android 开发中广泛应用。但它也有缺点,比如不支持注释和报错提示。在实际使用中,我们应该根据具体的需求选择合适的 JSON 解析库。