Search code examples
javajsonapiresponse

JsonObject Throws com.google.gson.stream.MalformedJsonException


I'm trying to get articles from a Newsapi.org and parse them in Java into a String to send these articles out with my Java Telegram-Abilities Bot. I tried using different method's for parsing the JSON in java.

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


Solution

  • Are you missing out the API GET method which is actually pulling your response?

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

    is currently just a string, as what is returned from that API is a well-formed JSON object