[Java] 讀取 JSON File

因為 json 廣泛流通,所以有滿多工具可以選擇

json.org

<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20210307</version>
</dependency>

沒提供由檔案轉 json 的建構子
因此必須先將檔案轉成 String
再由 String 建立 json 物件

使用 java.io

BufferedReader br = new BufferedReader(new FileReader(new File(pathname)));
StringBuffer sb = new StringBuffer();
String line;
while ((line = br.readLine()) != null) {
    sb.append(line);
}

JSONObject jsonObject = new JSONObject(sb.toString());

使用 java.nio

String json = new String(Files.readAllBytes(Paths.get(path)));
JSONObject jsonObject = new JSONObject(json);

Google json-simple

Mar 21, 2012 就不再更新了,似乎把重心轉往 Gson?

<!-- https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple -->
<dependency>
    <groupId>com.googlecode.json-simple</groupId>
    <artifactId>json-simple</artifactId>
    <version>1.1.1</version>
</dependency>
JSONObject jsonObject = (JSONObject) new JSONParser().parse(new FileReader(filename));

Clifton json-simple

近年還有更新,但冷門專案不推薦

<dependency>
    <groupId>com.github.cliftonlabs</groupId>
    <artifactId>json-simple</artifactId>
    <version>3.1.1</version>
</dependency>
JsonObject jsonObject = (JsonObject) Jsoner.deserialize(Files.newBufferedReader(Paths.get(filename)));

jackson、Gson、fastjson

除非是要轉換物件,否則不太適用