![](/img/trans.png)
[英]How can I find the value of an unnamed JSON object? (org.json) (java)
[英]Can not find the Json object (Using org.json)
Microsoft Academic提供了一個API,用於從Microsoft學術中獲取一些常規信息。 響應類型是Json對象。 使用org.Json和以下代碼,我試圖讀取響應對象,但我失敗了(需要下載這些 jar + common-logging和common-codec):
URIBuilder builder = new URIBuilder("https://api.projectoxford.ai/academic/v1.0/evaluate?");
builder.setParameter("expr", "Composite(AA.AuN=='jaime teevan')");
builder.setParameter("count", "100");
builder.setParameter("attributes", "Ti,CC");
URI uri = builder.build();
HttpGet request = new HttpGet(uri);
request.setHeader("Ocp-Apim-Subscription-Key", "Your-Key");
HttpClient httpclient = HttpClients.createDefault();
HttpResponse response = httpclient.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
JSONObject obj = new JSONObject(entity);
JSONArray arr = obj.getJSONArray("entities");
for (int i = 0; i < arr.length(); i++){
String post_id = arr.getJSONObject(i).getString("Ti");
System.out.println(post_id);
}
System.out.println(EntityUtils.toString(entity));
}
返回以下異常:
Exception in thread "main" org.json.JSONException: JSONObject["entities"] not found.
at org.json.JSONObject.get(JSONObject.java:471)
at org.json.JSONObject.getJSONArray(JSONObject.java:618)
如何解決這個問題?
編輯雖然很容易看到我在問題開頭提供的鏈接響應示例(Microsoft Academic),但為了方便讀者,我在這里展示:
{
"expr": "Composite(AA.AuN=='jaime teevan')",
"entities":
[
{
"logprob": -15.08,
"Ti": "personalizing search via automated analysis of interests and activities",
"CC": 372,
},
{
"logprob": -15.389,
"Ti": "the perfect search engine is not enough a study of orienteering behavior in directed search",
"CC": 237,
}
]
}
對我來說似乎問題是你沒有將你的響應轉換為string
,你需要在將響應轉換為JSONObject
之前將其轉換為string
HttpEntity entity = response.getEntity();
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
entity.writeTo(os);
} catch (IOException e1) {
}
String contentString = new String(os.toByteArray());
或者其他方式
InputStream instream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
String contentString = sb.toString(); // you can pass sb.toString() directly to jsonobject as well
現在將contentString
傳遞給JSONObject
JSONObject obj = new JSONObject(contentString);
JSONArray arr = obj.getJSONArray("entities");
更新:您也可以使用@ÖmerFadılUsta建議的這個 ,但我強烈建議使用HttpURLConnection
來提高安全性和性能
嘗試將字符串JsonData傳遞給JSONObject:
if (entity != null) {
String jsonData = EntityUtils.toString(entity);
JSONObject obj = new JSONObject(jsonData);
........
.....
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.