以下是一个示例代码,使用 Java 读取文件并返回 JSON:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class ReadFileToJson {
    public static void main(String[] args) throws IOException {
        String filePath = 'file.txt';
        String jsonString = readFile(filePath);
        JSONObject jsonObject = JSON.parseObject(jsonString);
        System.out.println(jsonObject.toJSONString());
    }

    public static String readFile(String filePath) throws IOException {
        BufferedReader reader = new BufferedReader(new FileReader(filePath));
        StringBuilder stringBuilder = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            stringBuilder.append(line);
        }

        reader.close();
        return stringBuilder.toString();
    }
}

在上面的示例中,我们首先定义了一个filePath变量来指定要读取的文件路径。然后,我们使用readFile方法读取文件并将其存储在一个字符串变量jsonString中。接下来,我们使用JSON.parseObject方法将字符串转换为JSON对象。最后,我们使用toJSONString方法将JSON对象打印到控制台。

请注意,此示例假定文件中包含有效的JSON数据。如果文件不包含有效的JSON数据,则可能会抛出异常。

Java 使用 FastJson 读取文件并返回 JSON 对象

原文地址: https://www.cveoy.top/t/topic/l4m2 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录