java.lang.ClassCastException: java.lang.String cannot be cast to org.json.JSONObject

Jerry :

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?

user404 :

follow the steps:

  1. get body string: String bodyString= resp.getString("body");
  2. parse bodyString to jsonObject: JSONObject body= new JSONObject(bodyString);
  3. get the username: String usename= body.getString("username");

This should work.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=25083&siteId=1