当前位置: 首页 > 知识库问答 >
问题:

java.lang.ClassCastException:java.lang.String不能强制转换为org.json.JsonObject

公良阳波
2023-03-14

我点击API,得到的响应是

{"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,}
java.lang.ClassCastException: java.lang.String cannot be cast to org.json.JSONObject

我试图获取用户名的逻辑。

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");

我做错了什么?

共有1个答案

桂学
2023-03-14

请执行以下步骤:

  1. 获取正文字符串:string bodyString=resp.getString(“body”);
  2. 将bodyString解析为JSONObject:JSONObject body=new JSONObject(bodyString);
  3. 获取用户名:String usename=body.getString(“username”);

这应该管用。

 类似资料: