租用问题

质量为本、客户为根、勇于拼搏、务实创新

< 返回租用问题列表

fastjson如何读取json文件,fastjson获取key

发布时间:2023-12-23 21:58:16

fastjson如何读取json文件

使用fastjson库读取JSON文件的步骤以下:

  1. 导入fastjson库的相关类和方法。
  2. 使用java.io包中的FileReader类读取JSON文件。
  3. 创建一个JSONReader对象,将FileReader对象作为参数传入。
  4. 调用JSONReader对象的readObject方法读取JSON文件内容。
  5. 关闭JSONReader对象和FileReader对象。

下面是一个示例代码:

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");
            
            // 创建JSONReader对象,将FileReader对象作为参数传入
            JSONReader jsonReader = new JSONReader(fileReader);
            
            // 调用readObject方法读取JSON文件内容
            JSONObject jsonObject = JSON.parseObject(jsonReader.readObject().toString());
            
            // 打印JSON对象
            System.out.println(jsonObject);
            
            // 关闭JSONReader和FileReader
            jsonReader.close();
            fileReader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

在上述示例中,假定JSON文件的名称为example.json。代码通过FileReader读取JSON文件内容,并使用JSONReader进行解析,最后将解析得到的JSON对象打印出来。