0

I will like to use the JSON response inside a controller. I am calling a method that returns the JSON. See my code below. Please how do I loop through the Json object returned inside my controller. I need to use the properties like sending mail to the email addresses from another method inside my controller .

My method that does that returns the JSON :

@ResponseBody
private ResponseEntity<?> queryIsw(String ref, String amt) throws Exception{
    String pdtid = "62";
    String salt = "D3D1D05AFE42AD50818167EAC73C109168A0F108";
    RestTemplate restt = new RestTemplate();
    String uri = "https://bestng.com/gettransaction.json";
    MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
    params.add("productid", pdtid);
    params.add("transactionreference", ref);
    params.add("amount", amt);
    UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl(uri).queryParams(params).build();
    URI oro = uriComponents.toUri();
    HttpHeaders hea = new HttpHeaders();
    String hs = pasher(pdtid, ref, salt);
    hea.add("hash", hs);
    HttpEntity<String> hent = new HttpEntity<String>(hea);

    ResponseEntity<Object> resp =  restt.exchange(oro, HttpMethod.GET, hent, Object.class);     

    return resp;

}

Below is my call to this method above from another method :

ResponseEntity<?> dres = queryIsw(dref,ama);

Kindly explain how I can use properties of 'dres' returned in my controller .

Thanks

Femi Adigun
  • 59
  • 2
  • 10

2 Answers2

0

Try taking a look at the Jackson JSON to Java mapping tools and specifically the ObjectMapper. It can convert a properly formatted JSON string into an object hierarchy from which you can pull out the data that you need. Jackson is a frequently used tool for this activity. Take a look at the tutorial for more details:

http://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/

If you need more help, do ask.

Jason K.
  • 790
  • 1
  • 14
  • 22
0

I am assuming that it will return within the body of the ResponseEntity.

Try:

String body = dres.getBody();

You can use something that can parse that string to a json object. Something like:

JSONObject jObject  = new JSONObject(body);

See:

http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/http/ResponseEntity.html

Java String to JSON conversion

Community
  • 1
  • 1
Hieu Le
  • 738
  • 4
  • 8
  • I was having issues adding JSON-LIB with maven. I got the info on how to do this from the link below and that solved it for me .:http://stackoverflow.com/questions/4173214/maven-missing-net-sf-json-lib. Thanks – Femi Adigun Sep 21 '15 at 17:31
  • Glad it worked out! if my answer helped you, would u mind marking it as accepted? @FemiAdigun – Hieu Le Sep 21 '15 at 17:59