2

I have a problem with this Json file. I am trying to do a Parser that shows in a textview the results after a button is pressed. I wonna parse the "firstName" tag but to do this, I need to pass through the others tags like "league" and "standard". I don't know how to parse them in this Json file. The Json file is structured like this:

{  
"_internal":{  
  "pubDateTime":"2017-06-23 03:21:52.076",
  "xslt":"xsl/league/roster/marty_active_players.xsl",
  "eventName":"league_roster"
},
"league":{  
  "standard":[  
     {  
        "firstName":"Alex",
        "lastName":"Abrines",
        "personId":"203518",
        "teamId":"1610612760 1610612760",
        "jersey":"8",
        "pos":"G-F",
        "heightFeet":"6",
        "heightInches":"6",
        "heightMeters":"1.98",
        "weightPounds":"190",
        "weightKilograms":"86.2",
        "dateOfBirthUTC":"1993-08-01",
        "teams":[  
           {  
              "teamId":"1610612760",
              "seasonStart":"2016",
              "seasonEnd":"2016"
           }
        ],
        "draft":{  
           "teamId":"1610612760",
           "pickNum":"32",
           "roundNum":"2",
           "seasonYear":"2013"
        },
        "nbaDebutYear":"2016",
        "yearsPro":"0",
        "collegeName":"",
        "lastAffiliation":"Spain/Spain",
        "country":"Spain"
     },

This is my Java code:

public class MainActivity extends AppCompatActivity {
Button btnHit;
TextView txtJson;
ProgressDialog pd;
String Players[] = new String[100];

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btnHit = (Button) findViewById(R.id.btn);
    txtJson = (TextView) findViewById(R.id.tvJsonItem);
    btnHit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new JsonTask().execute("http://data.nba.net/10s/prod/v1/2016/players.json");
        }
    });
}

private class JsonTask extends AsyncTask<String, String, String> {
    protected void onPreExecute() {
        super.onPreExecute();
        pd = new ProgressDialog(MainActivity.this);
        pd.setMessage("Please wait");
        pd.setCancelable(false);
        pd.show();
    }

    protected String doInBackground(String... params) {
        HttpURLConnection connection = null;
        BufferedReader reader = null;
        try {
            URL url = new URL(params[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();
            InputStream stream = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(stream));
            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = reader.readLine()) != null) {
                buffer.append(line + "\n");
                Log.d("Response: ", "> " + line);   //here u ll get whole response...... :-)
            }
            return buffer.toString();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        try {
            JSONObject jsonObject = new JSONObject(result);
            String DataPlayers = jsonObject.getString("standard");
            JSONArray jsonArray = new JSONArray(DataPlayers);
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject JO = jsonArray.getJSONObject(i);
                Players[i] = JO.getString("firstName");
                txtJson.append(Players[i] + "\n");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (pd.isShowing()) {
            pd.dismiss();
        }
    }
}
Wes
  • 266
  • 1
  • 3
  • 13

2 Answers2

2

Wrong:

JSONObject jsonObject = new JSONObject(result);
String DataPlayers = jsonObject.getString("standard");

Correct:

JSONObject jsonObject = new JSONObject(result);
JsonObject objStandard = jsonObject.getJSONObject("league");

Now from objStandard object, you can retrieve the json array and iterate through the sub json objects.

JSONArray jsonArray = objStandard.getJSONArray("standard");
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject JO = jsonArray.getJSONObject(i);
            Players[i] = JO.getString("firstName");
            txtJson.append(Players[i] + "\n");
        }

2 cents suggestion :)

It seems you have just started exploring android development, saying based on you are using a legacy method of json parsing, I would suggest you to check out GSON library, which is a Java serialization/deserialization library to convert Java Objects into JSON and back. In short, you will not be needed to parse JSON response manually but rather you will be having normal java class objects and members/methods to deal with.

Paresh Mayani
  • 127,700
  • 71
  • 241
  • 295
1

Your code should be like this

try {
        String result = "your_json_string";
        JSONObject jsonObject = new JSONObject(result);
        JSONObject leagueObject = jsonObject.getJSONObject("league");
        JSONArray standardArray = leagueObject.getJSONArray("standard");

        for (int i = 0; i < standardArray.length(); i++) {
            JSONObject standardObject = standardArray.getJSONObject(i);
            String name = standardObject.getString("firstName");
        }
    } catch (Exception e) {
        System.out.println(e);
    }