[
{
"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.