简体   繁体   中英

Parsing a JSON in Java on android studio?

    public void animeCall() {
        OkHttpClient client = new OkHttpClient();
        String URL = "https://animechan.vercel.app/api/random";
        Request request = new Request.Builder()
                .url(URL)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    final String myResponse = response.body().string();
                    String myFormattedAnimeQuote = "";
                    try {
                        //JSONObject to parse my OkHttp response.
                        JSONArray jsonarray = new JSONArray(myResponse);
                        for (int i = 0; i < jsonarray.length(); i++) {
                            JSONObject obj = jsonarray.getJSONObject(i);
                            String character = obj.getString("character");
                            String anime = obj.getString("anime");
                            String quote = obj.getString("quote");
                            myFormattedAnimeQuote = anime + ": " + quote + ": " + character;
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    final String myFinalQuote = myFormattedAnimeQuote;
                    MainActivity.this.runOnUiThread(() -> {
                        if (!myFinalQuote.equals("")) {
                            textView.setText(myFinalQuote);
                        } else {
                            textView.setText(myResponse);
                        }
                    });
                }
            }
        });
    }
}

Hello this is the code that i came up with to parse a JSONObject from the provided link it goes to the website and im trying to display the parsed data but for some reason it keeps returning the entire response not parsed any suggestions i believe im on the right track.

The URL you're requesting returns a JSON object, not a JSON array. You need to replace the code inside your try block with this:

        JSONObject obj = new JSONObject(myResponse);
        String character = obj.getString("character");
        String anime = obj.getString("anime");
        String quote = obj.getString("quote");
        myFormattedAnimeQuote = anime + ": " + quote + ": " + character;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM