0

This is my first time working with Android and I need to parse the JSON nested from the API. In the example below I managed to parse one JSON object, the value "title" is https://jsonplaceholder.typicode.com/posts/1. How do I change the code to look through all the JSON objects in the loop and extract "title" from them - https://jsonplaceholder.typicode.com/posts/?

P.S. If possible, I would not like to use the new Maven/Gradle dependencies.

package org.newwheel.app;

import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.util.JsonReader;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

import javax.net.ssl.HttpsURLConnection;


public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new RequestAsync().execute();
    }
    public class RequestAsync extends AsyncTask<String,String,List<String>> {

        @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        @Override
        protected List<String> doInBackground(String... strings) {

            List<String> projectList = new ArrayList<>();

            try {
                // Create URL
                URL newWheelEndpoint = new URL("https://jsonplaceholder.typicode.com/posts/1");
                // Create connection
                HttpsURLConnection myConnection = (HttpsURLConnection) newWheelEndpoint.openConnection();

                if (myConnection.getResponseCode() == 200) {
                    InputStream responseBody = myConnection.getInputStream();
                    InputStreamReader responseBodyReader = new InputStreamReader(responseBody, StandardCharsets.UTF_8);
                    JsonReader jsonReader = new JsonReader(responseBodyReader);
                        jsonReader.beginObject(); // Start processing the JSON object
                        while (jsonReader.hasNext()) { // Loop through all keys
                            String key = jsonReader.nextName(); // Fetch the next key
                            if (key.equals("title")) { // Check if desired key
                                // Fetch the value as a String
                                String value = jsonReader.nextString();

                                // Do something with the value
                                // ...
                                projectList.add(value);
                                break; // Break out of the loop
                            } else {
                                jsonReader.skipValue(); // Skip values of other keys
                            }

                        }
                    jsonReader.close();
                    myConnection.disconnect();
                } else {
                    // Error handling code goes here
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            return projectList;
        }

        @Override
        protected void onPostExecute(List<String> list) {
            if(list!=null){
                String[] array = list.toArray(new String[0]);

                // Get element ListView
                ListView countriesList = (ListView) findViewById(R.id.countriesList);

                // Create adapter
                ArrayAdapter<String> adapter = new ArrayAdapter(MainActivity.this,
                        android.R.layout.simple_list_item_1, array);

                // Install for list adapter
                countriesList.setAdapter(adapter);
            }
        }


    }
}
HtmlMan
  • 45
  • 2
  • 9
  • 1
    Does this answer your question? [How to parse JSON in Java](https://stackoverflow.com/questions/2591098/how-to-parse-json-in-java) – fuzious Apr 23 '20 at 22:01
  • Thank you for the link, I've already seen it in the Google search engine. I would like to use the Android SDK without the new Maven/Gradle dependencies. – HtmlMan Apr 23 '20 at 22:40
  • @HtmlMan the first, accepted, highly upvoted answer to that question describes how to do exactly that. [`org.json` is built into the Android SDK](https://developer.android.com/reference/org/json/package-summary) – Ryan M Apr 24 '20 at 01:29
  • For how to use JsonReader, specifically, it would help to describe the exact behavior you expected, as well as how that behavior differs from what is happening with your current implementation. Include the exact text of any error messages.. Your code is pretty close, you just need to wrap the object parsing into a similarly structured array parsing with `beginArray`. It looks like you're missing an `endObject` as well. See https://developer.android.com/reference/android/util/JsonReader#parsing-json – Ryan M Apr 24 '20 at 01:31

0 Answers0