Philo Philo - 4 months ago 8
JSON Question

Send JSON objefct as Post request to WebAP in JAVA

I am converting a string 'input' to a JSON object as:-

/* initialize Json object */
JSONObject jsonobj;

/* format input string as JSON object */
try {
JSONParser parser = new JSONParser();
jsonobj = (JSONObject) parser.parse(input);
}
catch (org.json.simple.parser.ParseException e) {
e.printStackTrace();
}


Previously, I could use the string 'input' and send it to the webapi as a POST request as follows:-

OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();


However, I am trying to send it in JSON format to the webapi, and hence have to convert the string 'input' and then send the JSON formatted object 'jsonobj'.... But I cannot seem to be be able to send the jsonobj as:-
os.write(jsonobj)


Any ideas on what I need to do to be able send the json object to the webapi?

Answer

Call toString() on the JSONObject. I've added it up into a single try/catch block as you pasted only fragments. You might want to split it as you need it.

try {
 JSONObject jsonobj;
 JSONParser parser = new JSONParser();
 jsonobj = (JSONObject) parser.parse(input);
 OutputStream os = conn.getOutputStream();
 // this does the trick:
 os.write(jsonobj.toString().getBytes());
 os.flush();
}
catch (Exception e) {
  e.printStackTrace();
}