使用fastjson庫(kù)讀取JSON文件的步驟如下:
下面是一個(gè)示例代碼:
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONReader;
import java.io.FileReader;
public class FastJsonDemo {
public static void main(String[] args) {
try {
// 使用FileReader讀取JSON文件
FileReader fileReader = new FileReader("example.json");
// 創(chuàng)建JSONReader對(duì)象,將FileReader對(duì)象作為參數(shù)傳入
JSONReader jsonReader = new JSONReader(fileReader);
// 調(diào)用readObject方法讀取JSON文件內(nèi)容
JSONObject jsonObject = JSON.parseObject(jsonReader.readObject().toString());
// 打印JSON對(duì)象
System.out.println(jsonObject);
// 關(guān)閉JSONReader和FileReader
jsonReader.close();
fileReader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
在上述示例中,假設(shè)JSON文件的名稱為example.json。代碼通過(guò)FileReader讀取JSON文件內(nèi)容,并使用JSONReader進(jìn)行解析,最后將解析得到的JSON對(duì)象打印出來(lái)。