How to read a JSON from a second link of an API?

Asked

Viewed 693 times

2

Speak guys, trying to get JSON, a second link that is provided by the API. But it gives error. Follows the code:

private static String URL = "https://google-play-api-znbelznpav.now.sh/api/apps/com.fungames.sniper3d/reviews/?lang=pt-br";

private void leitorJson(String url)
    throws URISyntaxException, JSONException, MalformedURLException, IOException {
    JSONTokener tokener = null;
    JSONObject principal = null;
    JSONArray arrayDeJson = null;
    String urlSegundaVez = null;
    URI urlAPI = new URI(url);
    do {
        if (urlSegundaVez == null) {
            tokener = new JSONTokener(urlAPI.toURL().openStream());

            principal = new JSONObject(tokener);

            arrayDeJson = principal.getJSONArray("results");
        } else {

            URI segundaURL = new URI(urlSegundaVez);

            tokener = new JSONTokener(segundaURL.toURL().openStream());

            principal = new JSONObject(tokener);

            arrayDeJson = principal.getJSONArray("results");
        }

        ArrayList<String> objetosJSON = new ArrayList<String>();

        int tamanho = arrayDeJson.length();

        for (int i = 0; i < tamanho; i++) {
            String novoObjtoJSON = arrayDeJson.getJSONObject(i).getString("text").replaceAll("Resenha completa",
                    " ");
            System.out.println(novoObjtoJSON.toString());
            objetosJSON.add(novoObjtoJSON);
        }
            tokener = null;
            arrayDeJson = null;
            urlSegundaVez = null;
            urlSegundaVez = principal.get("next").toString();
            principal = null;
    } while (urlSegundaVez != null);

}

However it gives error, when I will get the JSON of the second link, which I take:

urlSegundaVez = principal.get("next").toString();

I do not understand why this error occurs, since the JSON of the second link has the same format as the first one. The following error:

 org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]
    at org.json.JSONTokener.syntaxError(JSONTokener.java:451)
    at org.json.JSONObject.<init>(JSONObject.java:195)
    at com.rayner.arhf.testes.Testes.leitorJson(Testes.java:59)
    at com.rayner.arhf.testes.Testes.main(Testes.java:33)

1 answer

2


(Great chance to be my ignorance but...) I’ve never seen read data from the internet directly by the URI class, when I did a project that read JSON’s I used the following method:

URL url = new URL("http://exemplo.com/arquivo.json");
Scanner scanner;
scanner = new Scanner(url.openStream());
String json = scanner.next();
while (scanner.hasNext()) json += " "+scanner.next();
return new JSONObject(json);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.