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

Khác biệt giữa org.json.simple và org.json thư viện (Java)

Hai thư viện JSON phổ biến đầu đời Java: json-simple (org.json.simple) và json.org (org.json - by Douglas Crockford).

Bảng so sánh

Đặc điểm org.json.simple (json-simple) org.json (json.org)
Mục đích Encode/decode JSON đơn giản Parse JSON + convert JSON↔XML, HTTP header, Cookie, CDL
Class chính JSONValue, JSONObject, JSONArray, JsonString, JsonNumber JSONObject, JSONTokener, JSONWriter, JSONArray, CDL, Cookie, CookieList
Jar file json-simple.jar json.jar
Maven Central com.googlecode.json-simple:json-simple org.json:json
License Apache 2.0 JSON license (có clause "The Software shall be used for Good, not Evil")
Trạng thái Low maintenance Still maintained (sporadic)

Ví dụ json-simple

import org.json.simple.JSONObject;

public class SimpleJsonTest {
    public static void main(String[] args) {
        JSONObject obj = new JSONObject();
        obj.put("empName", "Raja");
        obj.put("employeeId", "115");
        obj.put("age", "30");
        System.out.println(obj.toJSONString());
    }
}
// Output: {"empName":"Raja","employeeId":"115","age":"30"}

Ví dụ org.json

import org.json.*;

public class JsonOrgTest {
    public static void main(String[] args) throws JSONException {
        String json = "{Name:Jai,Age:25,Salary:25000.00}";
        JSONObject obj = new JSONObject(json);
        System.out.println(obj.toString());
    }
}
// Output: {"Salary":25000,"Age":25,"Name":"Jai"}

Khuyến nghị hiện nay

Cả hai đều cũ và không khuyến nghị cho dự án mới. Nên dùng:

  • Jackson (fasterxml.jackson) - Enterprise standard, performance, feature-rich.
  • Gson (Google) - Simple, lightweight, Android-friendly.
  • JSON-B (Jakarta EE standard) - YAML/JSON binding annotation-based.

Migration tips

  • json-simple → Jackson: ObjectMapper.writeValueAsString() / readValue().
  • org.json → Jackson: Tương tự, JSONObject tương thích một phần.
  • Cả Jackson/Gson đều handle null, date, generic type, polymorphism tốt hơn nhiều.