Java 找不到Json对象(使用org.Json)
提供了一个API以从Microsoft academic获取一些一般信息。响应类型是一个Json对象。使用以下代码,我尝试读取响应对象,但失败(需要下载jars+通用日志和通用编解码器): 如何解决这个问题 编辑 虽然很容易看到我在问题开头提供的链接(Microsoft Academic)中的响应示例,但为了便于读者阅读,我将其显示在这里:Java 找不到Json对象(使用org.Json),java,json,microsoft-cognitive,Java,Json,Microsoft Cognitive,提供了一个API以从Microsoft academic获取一些一般信息。响应类型是一个Json对象。使用以下代码,我尝试读取响应对象,但失败(需要下载jars+通用日志和通用编解码器): 如何解决这个问题 编辑 虽然很容易看到我在问题开头提供的链接(Microsoft Academic)中的响应示例,但为了便于读者阅读,我将其显示在这里: { "expr": "Composite(AA.AuN=='jaime teevan')", "entities": [ {
{
"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");
更新:你也可以使用@Ömer Fadıl Usta建议的方法
但我强烈建议使用
HttpURLConnection
以提高安全性和性能尝试将字符串JsonData传递给JSONObject:
if (entity != null) {
String jsonData = EntityUtils.toString(entity);
JSONObject obj = new JSONObject(jsonData);
........
.....
}
反应如何?你有没有收到错误信息?从错误消息中,您可以看到返回的对象中没有
实体
属性。请单击我问题中的第一个单词(Microsoft Academical)查看响应示例。当然,当我使用System.out.println(EntityUtils.toString(entity))时代码>我可以看到整个回答。请在问题中使用带有错误的新代码添加更新的子句,我希望您不会重复这两次entity.getContent()代码>在你的代码中我发现了我的错误,这就是为什么我删除了我的评论。愚蠢的错误。@Pavinethingh你确定吗?因为我已经在我的本地java平台(没有安装任何android SDK)和org.apache.http.util.EntityUtilsi中的EntityUtils上进行了尝试,我忘记了我的新java8设置中没有apache,我也打算给你这个,但是没有,因为我试过java8:P:P@PavneetSingh没有apache http客户端JAR,你怎么能使用HttpClient?因为我知道答案,但我没有测试它,我在提供调试服务的同时解决了数千个HttpClient问题,而且它在android中是一个长期以来被弃用的API,所以不要再使用它了另外,你可以建议你的答案作为我的编辑,而不是在阅读解决方案和帖子之后
JSONObject obj = new JSONObject(contentString);
JSONArray arr = obj.getJSONArray("entities");
if (entity != null) {
String jsonData = EntityUtils.toString(entity);
JSONObject obj = new JSONObject(jsonData);
........
.....
}