简体   繁体   English

从文件读取JSON数据以在StringEntity中使用

[英]Read JSON data from a file for use in StringEntity

I'm trying to read simple data from a JSON text file and convert to a StringEntity for use in an API POST request. 我正在尝试从JSON文本文件中读取简单数据,并转换为StringEntity,以便在API POST请求中使用。 Whilst my API post request works fine if the data is hardcoded as a StringEntity, I am struggling to successfully parse the data. 如果将数据硬编码为StringEntity,我的API发布请求也可以正常工作,但我仍在努力地成功解析数据。 All prospective solutions I've googled deal with arrays which over complicate things for me. 我搜索过的所有预期解决方案都处理了使我的事情复杂化的数组。

Here is a sample of the JSON text file: 这是JSON文本文件的示例:

{
"data":"d1",
"data2":"d2",
"data3":"d3"
}

Here is the code I am using to try and import the data. 这是我用来尝试导入数据的代码。

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);

I feel like I'm being really foolish here somewhere. 我觉得我在某处真的很愚蠢。 I am newbie. 我是新手。 The StringEntity is hardcoded in like this when this works, so this is how I need it imported and parsed: 当工作时,StringEntity会像这样硬编码,所以这就是我需要导入和解析它的方式:

StringEntity entity = new StringEntity("{\"data\":\"d1\",\"data2\":\"d2\",\"data3\":\"d3\"}");

Classes used: 使用的类:

import org.json.JSONObject;
import org.json.JSONArray;
import org.json.simple.parser.JSONParser;

Just in case anyone else is interested... ended up with the following solution as there was no need to parse or format the JSON: 以防万一其他人有兴趣...最终得到了以下解决方案,因为不需要解析或格式化JSON:

String data;
data = new String(Files.readAllBytes(Paths.get("file.json")));

Libraries needed: 需要的库:

import java.nio.file.Paths;
import java.nio.file.Files;

Since Java 11 you can do Java 11开始,您可以

var content = Files.readString(Pahts.get("file.json"));
JSONObject json = (JSONObject) new JsonParser().parse(content);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM