简体   繁体   中英

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

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\":\"johntest@example.com\",\"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?

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.

JSONObject is nothing but a map which works on key-value. If the value returned by a key is map(ie key-value pairs) then it can be cast into a JSONObject, but in your case getBody.get("username") returns johntest@example.com 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM