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

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

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 .:stackoverflow.com/questions/4173214/…. Thanks
Glad it worked out! if my answer helped you, would u mind marking it as accepted? @FemiAdigun

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.