JsonObject 抛出 com.google.gson.stream.MalformedJsonException
JsonObject Throws com.google.gson.stream.MalformedJsonException
我正在尝试从 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
您是否错过了 API GET 方法,它实际上是在拉取您的响应?
String json = ("newsapi.org/v2/top-headlines? country = de & category = business & apiKey = myapikeyhere ");
目前只是一个字符串,因为从 API 返回的是一个 well-formed JSON 对象
我正在尝试从 Newsapi.org 获取文章并在 Java 中将它们解析为字符串,以便使用我的 Java Telegram-Abilities Bot 发送这些文章。 我尝试使用不同的方法来解析 java.
中的 JSONimport 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
您是否错过了 API GET 方法,它实际上是在拉取您的响应?
String json = ("newsapi.org/v2/top-headlines? country = de & category = business & apiKey = myapikeyhere ");
目前只是一个字符串,因为从 API 返回的是一个 well-formed JSON 对象