1

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;
  • 1
    Why are you _parsing_ the json you already have if you want to return a json response anyways? Why don't you just read the file as text and pass that text to `StringEntity`? – Thomas Mar 20 '19 at 13:49
  • I want to send the JSON data as StringEntity to a separate remote API. The applet I'm building is a go-between for 2 separate systems. I am assuming I need to parse the raw json text file into a more acceptable format for httpPost – ImmortalViper Mar 20 '19 at 13:53
  • Do I not need to do this? – ImmortalViper Mar 20 '19 at 13:55
  • Well, json should be json (if they both adhere to the specification), at least the data in the text file and the hardcoded data doesn't seem to be different at all - except some whitespace differences which should not be an issue (if they are I'd suspect it's the linebreaks but you should be able to remove those). Did you try passing the file's contents directly to the post? – Thomas Mar 20 '19 at 13:56
  • Can you please post the stack Trace? – Filip123go Mar 20 '19 at 13:57
  • Even after parsing and reformatting the json it _should_ work. What's the content of `data`? You didn't mention you get an exception but if you do, we need that information (and the stacktrace). If you do get an exception then I assume the cast doesn't work - so please post the fully qualified classnames for `JSONParser` and `JSONObject` (or the imports you're using). – Thomas Mar 20 '19 at 13:59
  • I can't share the stack trace at the moment. – ImmortalViper Mar 20 '19 at 14:14
  • Edited to include imports. – ImmortalViper Mar 20 '19 at 14:16
  • @Thomas How would I read the whole file as text? That seems like it would be the best option although I was unaware I could. – ImmortalViper Mar 20 '19 at 14:17
  • [Reading text files](https://stackoverflow.com/questions/4716503/reading-a-plain-text-file-in-java) - note that the examples might make use of the system's default encoding, like your example does too, but that's not reccommended so use the variants that take an encoding and provide the correct one (the one the file was written in). Also please note that `org.json.simple.parser.JSONParser` will most likely _not_ return `org.json.JSONObject` but `org.json.simple.JSONObject` so the cast in your code is bound to fail. – Thomas Mar 20 '19 at 14:25
  • @Thomas Many thanks for your help with this. I ended up using a 2 line solution that's entirely efficient. Appreciated. – ImmortalViper Mar 21 '19 at 11:11

2 Answers2

0

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;
  • Are you declaring `String data` and assigning the value to `data` on 2 lines or is that just a typo? I further assume instead of `String.readAllBytes` it actually is `Files.readAllBytes()` so your code probably looks more like `String data = new String( Files.readAllBytes(Paths.get("file.json")));` – Thomas Mar 21 '19 at 11:22
  • Finally please note that creating strings from byte arrays without providing a charset is risky: if the file's encoding differs from the system's default charset you'll not get the string you want - so it would be wise to always provide a charset to the `String(byte[], xxx)` constructor where `xxx` either is the charset's name or a charset instance. – Thomas Mar 21 '19 at 11:28
  • Yes, there were a few typos (long day). Thanks for the heads up on the charset. I'm looking at headers for the HttpPost process so I'll add it then. – ImmortalViper Mar 21 '19 at 11:49
  • To clarify, this snippet proceeds to be converted to StringEntity for the HttpPost as per the question. – ImmortalViper Mar 21 '19 at 11:52
  • Adding it to the post headers would help as well but you should add it to the reading process too (i.e. when you convert the byte array to a string). In general you should specify the charset _every time_ you convert from string to bytes or vice versa otherwise you risk encoding errors right at that place. – Thomas Mar 21 '19 at 12:39
0

Since Java 11 you can do

var content = Files.readString(Pahts.get("file.json"));
JSONObject json = (JSONObject) new JsonParser().parse(content);
xuesheng
  • 2,948
  • 2
  • 25
  • 33