【发布时间】:2019-06-13 12:03:34
【问题描述】:
我正在尝试从 Newsapi.org 获取文章并将它们在 Java 中解析为字符串,以使用我的 Java Telegram-Abilities Bot 发送这些文章。 我尝试使用不同的方法来解析 java 中的 JSON。
import org.json.*;
import org.apache.http.*;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public String GetNews() {
StringBuilder random = new StringBuilder();
StringBuilder failed = new StringBuilder();
String json = ("https://newsapi.org/v2/top-headlines?country=de&category=business&apiKey=myapikeyhere");
try {
JsonObject jsonObject = new
JsonParser().parse(json).getAsJsonObject(); // PROBLEM HERE!!!! Throws
com.google.gson.stream.MalformedJsonException
String article =
jsonObject.getAsJsonObject("id").get("name").getAsString();
System.out.println(article);
//String status =
obj.getJSONObject("source").getString("name");
JsonArray arr = jsonObject.getAsJsonArray("articles");
for (int i = 0; i < 3; i++) {
String post_id =
arr.get(i).getAsJsonObject().get("id").getAsString();
System.out.println(post_id);
random.append(post_id);
}
return random.toString();
} catch (JsonSyntaxException ex) {
String post_id = ("Critical Error");
failed.append(post_id);
}
return failed.toString();
}
com.google.gson.stream.MalformedJsonException
【问题讨论】:
-
欢迎来到 SO。请阅读How to Ask 并注意我们需要更多/其他信息才能提供帮助。一般来说,当询问异常时,您应该发布堆栈跟踪,特别是如果
JsonParser.parse(json)抛出MalformedJsonException,那么我们必须看到解析器抱怨的 json。 -
请贴出导致异常的json
-
这里的内容太长了,可以在这里找到json的newsapi.org