Java - Convert json response from python

Viewed 86

I'm running a mail-parser (written in python) in java runtime exec:

ProcessBuilder processb = new ProcessBuilder("mailparser", "-f", "path to mail file", "-j");
Process process = processb.start();
BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
    
String s = "";
String line = "";
while ((s = stdInput.readLine()) != null) {
    line += s;
}

JSONObject json = new JSONObject(line);

I expect a json response but the json i get looks like this (it's not the whole json because is pritty long):

b'{\n  "mime-version": "1.0",\n  "x-bbounce": "251383442|3165745|name@company.co.il|97|0|1094|4",\n  "content-type": "multipart/alternative; \\n\\tboundary=\\"----E85308AFD03B4874842B50FC08B1E8C9\\"",\n  "x-received": "by 2002:a17:906:b24d:: with SM"}'

When I try to convert it to JSONObject I get:

Exception in thread "main" org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]
at org.json.JSONTokener.syntaxError(JSONTokener.java:505)
at org.json.JSONObject.<init>(JSONObject.java:215)
at org.json.JSONObject.<init>(JSONObject.java:399)
at Test.main(Test.java:169)

I tried to remove to "b" and the " ' " at the beginning and the end of the json, I even tried with jsonb and it still would not work.

If I'm runnig the exact command in CMD, I get perfect json with no "b" and " ' " and I can convert it.

How do i convert this json to JSONObject?

Edit: I dont have access to the python code

1 Answers

I would do as follows.

in Python, have the result built from a dictionary and return it as below:

example = {
  "key_a": 'value_a',
  "key_b": 'value_b'
}

print(json.dumps(example))

Then, in Java, you have

ProcessBuilder processb = new ProcessBuilder("mailparser", "-f", "path to mail file", "-j");
Process process = processb.start();
InputStream is = processb.getInputStream();
String resultString = IOUtils.toString(is, StandardCharset.UTF_8);

and from there you can convert the String to JSON.
Of course, instead of using IOUtils::toString, you can also use a BufferedReader.

Related