Reputation: 39
I hit the API, I get the response as
{"headers":{"Keep-Alive":["timeout=4, max=500"],"Server":["Apache"],"X-Content-Type-Options":["nosniff"],"Connection":["Keep-Alive"],"Vary":["X-Forwarded-For"],"X-XSS-Protection":["1;mode=block"],"Content-Length":["451"],"Content-Type":["application/hal+json"]},"statusCodeValue":200,"body":"{\"id\":\"7199\",\"username\":\"[email protected]\",\"start_time\":1583212261,\"expire_time\":1583253338,\"sponsor_profile\":\"1\",\"enabled\":false,\"current_state\":\"disabled\",\"notes\":null,\"visitor_carrier\":null,\"role_name\":\"[Guest]\",\"role_id\":2,}
Then I try to fetch the body.I get till body but I m not able to fetch username under body.Basically my main aim is to get the username.It throws this error
java.lang.ClassCastException: java.lang.String cannot be cast to org.json.JSONObject
Logic that I tried to get username.
ResponseEntity<String> resp = restTemplate.exchange(
reader.getAccountURL() + request.getUsername(),
HttpMethod.GET, entity, String.class);
JSONObject accountDetails = new JSONObject(resp);
Object getBody = accountDetails.get("body");
Object alreadyExits = ((JSONObject) getBody).get("username");
What m I doing wrong?
Upvotes: 0
Views: 5099
Reputation: 28
JSONObject is nothing but a map which works on key-value.
If the value returned by a key is map(i.e. key-value pairs) then it can be cast into a JSONObject, but in your case getBody.get("username")
returns [email protected]
which is a simple string and not a key-value pair hence you get this exception
Use: JSONObject getBody = accountDetails.getJsonObject("body")
or you can use:
String bodyString= accountDetails.getString("body");
JSONObject getBody= new JSONObject(bodyString)
and then use Object alreadyExits = ((String) getBody).get("username");
and it should work just fine.
Upvotes: 0
Reputation: 2028
follow the steps:
String bodyString= resp.getString("body");
JSONObject body= new JSONObject(bodyString);
String usename= body.getString("username");
This should work.
Upvotes: 2