gpt4 book ai didi

java - 找不到 Json 对象(使用 org.json)

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:13:51 27 4
gpt4 key购买 nike

Microsoft Academic提供了一个 API 来从 Microsoft academic 获取一些一般信息。响应类型是 Json 对象。使用org.Json和下面的代码,我试图读取响应对象,但我失败了(需要下载 these jars + 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 ,你需要将你的响应转换为 string 然后再传递给 JSONObject

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

更新:您也可以使用 this @Ömer Fadıl Usta 也建议但我强烈建议使用 HttpURLConnection 以确保安全性和性能

关于java - 找不到 Json 对象(使用 org.json),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39586409/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com