Get data in JSON

3
[
{
"ID": 1,
"ano": 5
}
]

I do not know how I get in JSON the value of each of the fields, in this case "1" and "5", as I present above.

In getting the data in JSON I tried to follow some tips that I have been looking for but in vain. I present below what I am currently trying, but without success.

public class JSONTask extends AsyncTask<String, String, String> {

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

            String finalJson = buffer.toString();

            JSONObject parentobject = new JSONObject(finalJson);
            JSONArray parentArray = parentobject.getJSONArray("");
            JSONObject finalObject = parentArray.getJSONObject(0);

            int id = finalObject.getInt("ID");
            int ano = finalObject.getInt("ano");

            return "id: " +id+ " ano: " +ano;

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException 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);
        System.out.println("Result: " + result);
        tvdata.setText(result);
    }
}

I can get all the content together, that is "[ { "ID": 1, "ano": 5 } ]" , but I find it difficult to get certain fields as I mentioned.

    
asked by anonymous 14.08.2017 / 13:02

1 answer

4

If the structure is exactly as it is in the question, you can do this:

String jsonString = "[{\"ID\":1,\"ano\":5}]";

JSONArray jsonArray = new JSONArray(jsonString);
JSONObject jsonObject = new JSONObject(jsonArray.get(0).toString());

System.out.println("ID: " + jsonObject.getInt("ID"));
System.out.println("ANO: " + jsonObject.getInt("ano"));

You can also do this:

String jsonString = "[{\"ID\":1,\"ano\":5}]";

JSONObject jsonObject = new JSONArray(jsonString).getJSONObject(0);

System.out.println("ID: " + jsonObject.getInt("ID"));
System.out.println("ANO: " + jsonObject.getInt("ano"));
    
14.08.2017 / 13:23