简体   繁体   中英

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. Whilst my API post request works fine if the data is hardcoded as a StringEntity, I am struggling to successfully parse the data. All prospective solutions I've googled deal with arrays which over complicate things for me.

Here is a sample of the JSON text file:

{
"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 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:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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