JsonObject引发com.google.gson.stream.MalformedJsonException

时间:2019-06-13 12:03:34

标签: java json api response

我正在尝试从Newsapi.org获取文章,并将其以Java解析为String,以便通过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

1 个答案:

答案 0 :(得分:0)

您是否错过了实际上在获取响应的API GET方法?

String json = ("newsapi.org/v2/top-headlines? country = de & category = business & apiKey = myapikeyhere ");

当前只是一个字符串,因为从该API返回的是格式正确的JSON对象