Spring : Convert Response Entity to JSON

21,477

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

Share:
21,477
sTg
Author by

sTg

~~I believe in learning and you learn every second in your life~~

Updated on July 09, 2022

Comments

  • sTg
    sTg almost 2 years

    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;
    }
    
  • sTg
    sTg about 6 years
    But how do i convert responseentity to json?
  • ojblass
    ojblass over 3 years
    this makes me so mad. GetforObject can unmarshal to an object automatically. Am I in the boat that I have to parse that with jackson now by hand?