【发布时间】:2020-03-04 20:02:42
【问题描述】:
我点击了 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");
我做错了什么?
【问题讨论】:
-
尝试
getJsonObject("body")而不是get("body")。 -
看起来您的响应是 HTTP 响应的 JSON 化。因此,主体只是一个字符串值,它编码另一个 JSON 对象,因此您需要再次解析
body值。 -
@Arnaud 当我这样做时,我得到了这个异常 org.json.JSONException: JSONObject["body"] is not a JSONObject。
-
@JoachimSauer。你能告诉我怎么做吗?