将Json数据解析为Json对象

时间:2019-02-08 12:11:14

标签: android json

我在解析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文件的代码:Get JSON Data from URL Using 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 个答案:

答案 0 :(得分:1)

您可以使用以下内容:

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

我一直在使用这种代码,就像是一种魅力。