fastjson怎么讀取json文件

小億
475
2023-12-23 21:58:16

使用fastjson庫(kù)讀取JSON文件的步驟如下:

  1. 導(dǎo)入fastjson庫(kù)的相關(guān)類和方法。
  2. 使用java.io包中的FileReader類讀取JSON文件。
  3. 創(chuàng)建一個(gè)JSONReader對(duì)象,將FileReader對(duì)象作為參數(shù)傳入。
  4. 調(diào)用JSONReader對(duì)象的readObject方法讀取JSON文件內(nèi)容。
  5. 關(guān)閉JSONReader對(duì)象和FileReader對(duì)象。

下面是一個(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)。

0