การ Parse JSON ใน Java มีหลายไลบรารี่ บทความนี้ครอบคลุม 3 ตัวยอดนิยม: org.json (เบา), Gson (Google), และ JsonPath (XPath สำหรับ JSON)
JSON ตัวอย่าง
{
"pageInfo": {
"pageName": "Homepage",
"logo": "https://www.example.com/logo.jpg"
},
"posts": [
{
"post_id": "0123456789",
"actor_id": "1001",
"author_name": "Jane Doe",
"post_title": "How to parse JSON in Java",
"comments": [],
"time_of_post": "1234567890"
}
]
}
1. org.json (Simple, Lightweight)
Dependency (Maven)
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20231013</version>
</dependency>
โค้ด org.json
import org.json.JSONArray;
import org.json.JSONObject;
public class ParseJsonOrgJson {
public static void main(String[] args) {
String json = "..."; // JSON string จากข้างต้น
JSONObject obj = new JSONObject(json);
// ดึงค่าจาก JSON Object
String pageName = obj.getJSONObject("pageInfo").getString("pageName");
System.out.println("Page Name: " + pageName); // Homepage
// ดึงค่าจาก JSON Array
JSONArray posts = obj.getJSONArray("posts");
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.getJSONObject(i);
String postId = post.getString("post_id");
String author = post.getString("author_name");
System.out.println("Post ID: " + postId + ", Author: " + author);
}
}
}
2. Gson (Google - แนะนำสำหรับ Production)
Dependency (Maven)
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.10.1</version>
</dependency>
โค้ด Gson
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class ParseJsonGson {
public static void main(String[] args) {
String json = "..."; // JSON string
JsonObject jsonObject = JsonParser.parseString(json).getAsJsonObject();
// ดึงค่า - ต้องใช้ get() แล้วตามด้วย getAsString()/getAsInt() ฯลฯ
String pageName = jsonObject.getAsJsonObject("pageInfo").get("pageName").getAsString();
System.out.println("Page Name: " + pageName);
JsonArray posts = jsonObject.getAsJsonArray("posts");
for (int i = 0; i < posts.size(); i++) {
String postId = posts.get(i).getAsJsonObject().get("post_id").getAsString();
System.out.println("Post ID: " + postId);
}
}
}
3. JsonPath (XPath for JSON - Query แบบไม่ต้อง Deserialize ทั้งหมด)
Dependency (Maven)
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.8.0</version>
</dependency>
โค้ด JsonPath
import com.jayway.jsonpath.JsonPath;
public class ParseJsonPath {
public static void main(String[] args) {
String json = "..."; // JSON string
// Query โดยตรง - ไม่ต้อง parse ทั้ง object
String pageName = JsonPath.read(json, "$.pageInfo.pageName");
System.out.println("Page Name: " + pageName);
// ดึงจำนวน posts
int postCount = JsonPath.read(json, "$.posts.length()");
// วนลูปดึง post_id ทุกตัว
for (int i = 0; i < postCount; i++) {
String postId = JsonPath.read(json, "$.posts[" + i + "].post_id");
System.out.println("Post ID: " + postId);
}
// หรือดึงทั้ง array เลย
List<String> allPostIds = JsonPath.read(json, "$.posts[*].post_id");
System.out.println("All Post IDs: " + allPostIds);
}
}
JsonPath Syntax Cheatsheet
| Syntax | หมายความ |
| $ | Root element |
| $.store.book | Key book ภายใน store |
| $..book | Key book ทุกระดับ (recursive) |
| $.store.book[0] | Element แรกของ array book |
| $.store.book[*] | ทุก element ของ array book |
| $.store.book[?(@.price < 10)] | Filter: price < 10 |
เปรียบเทียบ 3 ไลบรารี่
| คุณสมบัติ | org.json | Gson | JsonPath |
| Full Deserialization | ✅ | ✅ | ❌ (Query only) |
| Performance (Large JSON) | ⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ (Partial) |
| Type Safety | ❌ | ✅ (กับ POJO) | ❌ |
| Dependency Size | เล็ก | กลาง | กลาง |
| เหมาะสำหรับ | Simple parsing | Production, POJO mapping | Extract specific fields |
บทความเกี่ยวข้อง