0

I have a problem with parsing a tag inside a Json object. My json code is structured like that:

{"giocatori":[{"nome":"Giovanni","cognome":"Muchacha","numero":"1","ruolo":"F-G"},
{"nome":"Giorgio","cognome":"Rossi","numero":"2","ruolo":"AG"},
{"nome":"Andrea","cognome":"Suagoloso","numero":"3","ruolo":"P"},
{"nome":"Salvatore","cognome":"Aranzulla","numero":"4","ruolo":"G"},
{"nome":"Giulio","cognome":"Muchacha","numero":"5","ruolo":"F"}]}

I got the code that let me get the Json file from here: Get JSON Data from URL Using Android? and I'm trying to parse a tag (for example the "nome" tag) into a Json object. This is the code I got:

public class MainActivity extends AppCompatActivity {

Button btnHit;
TextView txtJson;
ProgressDialog pd;

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

btnHit = (Button) findViewById(R.id.btnHit);
txtJson = (TextView) findViewById(R.id.tvJsonItem);

btnHit.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        new JsonTask().execute("https://api.myjson.com/bins/177dpo");
    }
 });


}


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);   

        }

        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);
    if (pd.isShowing()){
        pd.dismiss();
    }
    txtJson.setText(result);
 }
}
}  

I've never worked with this type of file so I'll really appreciate your help!

3
  • you can generate POJO class using jsonschema2pojo.com Commented Feb 8, 2019 at 12:22
  • Can you make an example code so I understand what you mean and mark the question as answered, thank you Commented Feb 8, 2019 at 12:27
  • just copy your gson and paste it over there, I am behind firewall right now and cannot access that site. Commented Feb 8, 2019 at 12:28

1 Answer 1

0

You can use something like this:

try {
                    String servResponse = response.toString();
                    JSONObject parentObj = new JSONObject(servResponse);
                    JSONArray parentArray = parentObj.getJSONArray("giocatori");

                    if (parentArray.length() == 0) {
                        //if it's empty, do something (or not)

                    } else {
                        //Here, finalObj will have your jsonObject
                        JSONObject finalObj = parentArray.getJSONObject(0);
                        //if you decide to store some value of the object, you can do like this (i've created a nomeGiocatori for example)
                        nomeGiocatori = finalObj.getString("nome");

                    }

                } catch (Exception e) {
                    Log.d("Exception: ", "UnknownException");
                }

I use this kind of code all the time, works like a charm.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.