Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Parse JSON trong Java: Hướng dẫn toàn diện với các thư viện phổ biến

Hướng dẫn này trình bày cách parse JSON trong Java dùng các thư viện khác nhau.

JSON (JavaScript Object Notation) dựa trên tập con của JavaScript. Là định dạng trao đổi dữ liệu phổ biến trong web programming.

Dưới đây là JSON mẫu để parse lấy pageName, pagePic, post_id:

{
  "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"
    }
  ]
}

Parse JSON dùng org.json

Thêm dependency org.json từ Maven repository.

import org.json.JSONArray;
import org.json.JSONObject;

public class ParseJSON {
    static String json = "..."; // Chuỗi JSON ở trên
    public static void main(String[] args) {
        JSONObject obj = new JSONObject(json);
        String pageName = obj.getJSONObject("pageInfo").getString("pageName");
        System.out.println(pageName);
        JSONArray arr = obj.getJSONArray("posts");
        for (int i = 0; i < arr.length(); i++) {
            String post_id = arr.getJSONObject(i).getString("post_id");
            System.out.println(post_id);
        }
    }
}

Lưu ý: ... thay bằng chuỗi JSON thực tế. Đầu tiên chuyển JSON string thành JSONObject. "pageInfo" là JSON Object -> dùng getJSONObject. "posts" là JSON Array -> dùng getJSONArray.

  • Cách chuyển Java Object sang JSON
  • Cách chuyển Java Map sang JSON
  • Cách encode và decode JSON

Parse JSON dùng Gson

Thêm dependency Gson từ Maven repository.

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class ParseJSON {
    static String json = "...";
    public static void main(String[] args) {
        JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject();
        String pageName = jsonObject.getAsJsonObject("pageInfo").get("pageName").getAsString();
        System.out.println(pageName);
        JsonArray arr = jsonObject.getAsJsonArray("posts");
        for (int i = 0; i < arr.size(); i++) {
            String post_id = arr.get(i).getAsJsonObject().get("post_id").getAsString();
            System.out.println(post_id);
        }
    }
}

Parse JSON dùng JsonPATH

Hai ví dụ trên cần deserialize toàn bộ JSON trước khi truy cập giá trị. JsonPATH cho phép truy xuất trực tiếp như XPath cho JSON.

Thêm dependency JsonPATH từ Maven.

import com.jayway.jsonpath.JsonPath;

public class ParseJSON {
    static String json = "...";
    public static void main(String[] args) {
        String pageName = JsonPath.read(json, "$.pageInfo.pageName");
        System.out.println(pageName);
        Integer posts = JsonPath.read(json, "$.posts.length()");
        for (int i = 0; i < posts; i++) {
            String post_id = JsonPath.read(json, "$.posts[" + i + "].post_id");
            System.out.println(post_id);
        }
    }
}