java - JsonObject 抛出 com.google.gson.stream.MalformedJsonException

标签 java json api response

我正在尝试从 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 返回的是一个格式良好的 JSON 对象

关于java - JsonObject 抛出 com.google.gson.stream.MalformedJsonException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56580058/

相关文章:

java - JPA 中的多对多双向映射

java - 加载您自己的 SecurityManager 或禁用现有的

javascript - 不覆盖现有属性的Object.Assign()

c# - 如何使用 API 传输密码

javascript - JSON 未正确发布

java - 将对象存储到数组中 - Java

java - 我如何在 Retrofit 库中使用 Gson?

javascript - 如何在同一页面上创建多个谷歌地图(不是标记)?

php - 防止PHP超时

java - 如何在java swing中将组件放在图像上?