Разобрать данные Json в объект Json

1

У меня проблема с анализом тега внутри объекта Json. Мой код JSON структурирован так:

{"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"}]}

Я получил код, который позволяет мне получить файл Json отсюда: Получить данные JSON с URL-адреса Используя Android? и я пытаюсь разобрать тег (например, тег "nome") в объект Json. Вот код, который я получил:

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

Я никогда не работал с этим типом файла, поэтому я очень ценю вашу помощь!

Теги:

1 ответ

1
Лучший ответ

Вы можете использовать что-то вроде этого:

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

                    if (parentArray.length() == 0) {
                        //if it 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");
                }

Я использую этот вид кода все время, работает как шарм.

  • 0
    Работает отлично, спасибо!

Ещё вопросы

Сообщество Overcoder
Наверх
Меню