Working with JSON for request and response Java

1

I need to consume a WS with rest that is almost complete, only 2 things to finish: - mount the request JSON and manipulate the response. JSON

Here is an example of the template I need to submit in the request:

{
    "sendSmsRequest": {
        "to": "123456789",
        "msg": "funcionou"
    }
}   

To do this I'm trying to use JSON Object:

JSONObject jsonObject = new JSONObject();
jsonObject.put("to", "123456789");
jsonObject.put("msg", "funcionou");
StringEntity input = new StringEntity(jsonObject.toString());
   //parametros para montar o request(Headers e Entity)
...

However, when I start the test, I see that "sendSmsRequest" does not go into the request. If I mount a string containing the entire request,

String teste = "{\"sendSmsRequest\": { \"to\": \"123456789\",\"msg\": \"funcionou\"}}";

However, I need to find a more elegant solution. Is there any method in the JSON object that allows me to set this "header"?     

asked by anonymous 07.07.2017 / 16:43

2 answers

1

Try this way

JSONObject jsonObject = new JSONObject();
jsonObject.put("to", "123456789");
jsonObject.put("msg", "funcionou");

JSONObject json2 = new JSONObject();
json2.put("sendSmsRequest", jsonObject);
StringEntity input = new StringEntity(json2.toString());

The result will be what you expect

    
07.07.2017 / 18:50
0

Good morning,

I would recommend using Gson. It would make it much easier for you to handle these requests.

    
07.07.2017 / 16:47