Work with JSON for request and Java Sponse

Asked

Viewed 2,038 times

1

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

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

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

to do this I am 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 printing the test, I see that the "sendSmsRequest" does not go in the request. If I mount a string containing all the right request,

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

But I must find a more elegant solution.
Is there any method in JSON Object that allows me to set this "header"?

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

  • Opa Marquezani, thank you very much! I did it this way and came out perfectly!!

0

Good morning,

I would recommend the use of Gson. It would greatly facilitate your work for the treatment of these requests.

  • Opa Caio, I’ll do a search here. You would have some example of how to mount this request?

  • User user = new User(); user.setName("Test"); user.setUsername("many tests"); Gson gson = new Gson(); String userJSONString = gson.toJson(user);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.