Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring : Convert Response Entity to JSON

From my rest client, i am hitting a web service and getting my response in the form of String {"code":"00000","msg":"Success"> . Now I am converting this in the form of JSONObject which i can then use further. But i am not able to. Below is the code i am using . Please guide.

private ResponseEntity<String> test()
{
    final String uri = "URL";

    RestTemplate restTemplate = new RestTemplate();

    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    headers.setContentType(MediaType.APPLICATION_JSON);
    HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);       
    ResponseEntity<String> result = restTemplate.exchange(uri, HttpMethod.GET, entity, String.class);       
    System.out.println(result);

    //This part is not working.
    try {
        JSONObject arr = new JSONObject((result));
        for (int i = 0; i < arr.length(); i++) {
          JSONObject abc = arr.getJSONObject(i);
          System.out.println("test1 : " + abc.getString("test1"));
          System.out.println("test2 : " + abc.getString("test2"));
          System.out.println("test3 : " + abc.getString("test3"));
        }
    } catch (Exception e) {
    }

    return result;
}
like image 585
sTg Avatar asked Feb 15 '26 01:02

sTg


1 Answers

Instead of converting to a generic JSONObject, you should create a class matching your response.
Spring will map the response to your model class using Jackson(behind the scenes). There is no need for converting it yourself.

So Let's say, you create a class

class Response {
String code;
String message:

//Gettes and Setters
}

Now you can change your code a bit like this

 ResponseEntity<Response> result = restTemplate.exchange(uri, HttpMethod.GET, entity, Response.class);     

Now if you useresult.getBody(), this would give your Response object, which you can use

like image 60
pvpkiran Avatar answered Feb 16 '26 16:02

pvpkiran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!