Home > Software design >  Parse JSON data into Java Object Array
Parse JSON data into Java Object Array

Time:06-24

I am trying to gather json data and parse it into a java object, and then add it to an object array to later display into my list view & fragment. Here is my code:

import androidx.appcompat.app.AppCompatActivity;

import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    ArrayList<Character> characterArray = new ArrayList<Character>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        CharacterGetData characterGetData = new CharacterGetData();
        characterGetData.execute("https://swapi.dev/api/people/?format=json");
    }

//Character Class
class Character{
       String name;
       String height;
       String mass;

}

    class CharacterGetData extends AsyncTask<String, String, String> {
        String name;
        String height;
        String mass;


        @Override
        protected String doInBackground(String... args) {

            try {

                URL obj = new URL(args[0]);
                HttpURLConnection connection = (HttpURLConnection) obj.openConnection();
                connection.setRequestMethod("GET");


                BufferedReader in = new BufferedReader(
                        new InputStreamReader(connection.getInputStream()));
                String line;
                StringBuffer response = new StringBuffer();
                while ((line = in.readLine()) != null) {
                    response.append(line);

                }
                in.close();

                JSONObject jsonObj = new JSONObject(response.toString());
                Character character1 = new Character();
                character1.name = jsonObj.getString("name");
                character1.height = jsonObj.getString("height");
                character1.mass = jsonObj.getString("mass");
                characterArray.add(character1);


                Log.i("MainActivity", "The name is "   character1.name   "the height is "   character1.height);


            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException | JSONException e) {
                e.printStackTrace();
            }
            return null;
        }
    }}

The code runs properly, but when trying to confirm the results with the log message I am receiving the following in debugger:

W/System.err: org.json.JSONException: No value for name
W/System.err:     at org.json.JSONObject.get(JSONObject.java:400)
W/System.err:     at org.json.JSONObject.getString(JSONObject.java:561)
W/System.err:     at com.example.androidlabs.MainActivity$CharacterGetData.doInBackground(MainActivity.java:71)
W/System.err:     at com.example.androidlabs.MainActivity$CharacterGetData.doInBackground(MainActivity.java:43)
W/System.err:     at android.os.AsyncTask$3.call(AsyncTask.java:394)
W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:266)
W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:305)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
W/System.err:     at java.lang.Thread.run(Thread.java:923)

The JSON data( found at https://swapi.dev/api/people/?format=json) looks like :

{"count":82,"next":"https://swapi.dev/api/people/?page=2&format=json","previous":null,"results":[{"name":"Luke Skywalker","height":"172","mass":"77","hair_color":"blond","skin_color":"fair","eye_color":"blue","birth_year":"19BBY","gender":"male","homeworld":"https://swapi.dev/api/planets/1/","films":["https://swapi.dev/api/films/1/","https://swapi.dev/api/films/2/","https://swapi.dev/api/films/3/","https://swapi.dev/api/films/6/"],"species":[],"vehicles":["https://swapi.dev/api/vehicles/14/","https://swapi.dev/api/vehicles/30/"],"starships":["https://swapi.dev/api/starships/12/","https://swapi.dev/api/starships/22/"],"created":"2014-12-09T13:50:51.644000Z","edited":"2014-12-20T21:17:56.891000Z","url":"https://swapi.dev/api/people/1/"}

You can see that there is a name tag, so I am not sure why I am getting this error, nor how to fix this. I also tried using a JSONArray but also got an error. Any suggestions would be appreciated!

CodePudding user response:

You should get the result JSONArray from the response JSONObject and iterate through it like the following.

JSONObject jsonObj = new JSONObject(response.toString());
JSONArray jsonArray = jsonObj.getJSONArray("results");
for (int i = 0 ; i < jsonArray.length(); i  ) {
     JSONObject charecterObj = jsonArray.getJSONObject(i);
     Character character1 = new Character();
     character1.name = charecterObj.getString("name");
     character1.height = charecterObj.getString("height");
     character1.mass = charecterObj.getString("mass");
     characterArray.add(character1);
    }
  • Related