java - 从文件中读取 JSON 数据以在 StringEntity 中使用
问题描述
我正在尝试从 JSON 文本文件中读取简单数据并转换为 StringEntity 以用于 API POST 请求。虽然如果数据被硬编码为 StringEntity,我的 API 发布请求工作正常,但我正在努力成功解析数据。我用谷歌搜索的所有潜在解决方案都处理对我来说过于复杂的数组。
这是 JSON 文本文件的示例:
{
"data":"d1",
"data2":"d2",
"data3":"d3"
}
这是我用来尝试导入数据的代码。
JSONParser parser = new JSONParser();
JSONObject a = new JSONObject();
try {
FileReader fileReader = new FileReader("/directory/file.json");
a = (JSONObject) parser.parse(fileReader);
} catch (Exception e1) {
e1.printStackTrace();
}
String data = a.toString();
StringEntity entity = new StringEntity(data);
entity.setContentType(ContentType.APPLICATION_JSON.getMimeType());
request.addHeader("Accept", acceptHeader);
request.setEntity(entity);
HttpResponse response = client.execute(request);
我觉得我在这里某个地方真的很愚蠢。我是新手。当它工作时,StringEntity 是这样硬编码的,所以这就是我需要它导入和解析的方式:
StringEntity entity = new StringEntity("{\"data\":\"d1\",\"data2\":\"d2\",\"data3\":\"d3\"}");
使用的类:
import org.json.JSONObject;
import org.json.JSONArray;
import org.json.simple.parser.JSONParser;
解决方案
以防万一其他人感兴趣......最终得到以下解决方案,因为不需要解析或格式化 JSON:
String data;
data = new String(Files.readAllBytes(Paths.get("file.json")));
需要的库:
import java.nio.file.Paths;
import java.nio.file.Files;
推荐阅读
- bitmap - 如何在 Rider 调试会话中预览位图?
- python - 从字典、嵌套字典、列表中获取键并检查它出现的次数
- lua - 如何为乒乓球游戏添加边框,以便球从 Lua 上的黑线反弹
- r - 如何将 GitHub 中的 png 加载到 R 中?
- r - 生成重复并将矩阵转换为df
- java - 如何停止强制子类实现父构造函数
- c# - IIS 上托管的 Asp.Net Core 中间件响应重定向 URL 不完整
- amazon-web-services - Kubectl 命令给出连续的连接错误
- c# - 在(隔离的)Azure 函数中运行用户制作的 C# 代码是否安全?
- powerbi - DAX 有条件地从不同的列求和?