Soy principiante en Android. En mi proyecto, estoy recibiendo la siguiente json de la respuesta HTTP.
[{"Date":"2012-1-4T00:00:00",
"keywords":null,
"NeededString":"this is the sample string I am needed for my project",
"others":"not needed"}]
Quiero obtener el "NeededString" de la json anterior. ¿Cómo obtenerlo?
Esto podría ayudarte.
Java:
JSONArray arr = new JSONArray(result);
JSONObject jObj = arr.getJSONObject(0);
String date = jObj.getString("NeededString");
Kotlin:
val jsonArray = JSONArray(result)
val jsonObject: JSONObject = jsonArray.getJSONObject(0)
val date= jsonObject.get("NeededString")
Sólo necesitas obtener el JSONArray
e iterar el JSONObject
dentro del Array usando un bucle aunque en tu caso es sólo un JSONObject pero puedes tener más.
JSONArray mArray;
try {
mArray = new JSONArray(responseString);
for (int i = 0; i < mArray.length(); i++) {
JSONObject mJsonObject = mArray.getJSONObject(i);
Log.d("OutPut", mJsonObject.getString("NeededString"));
}
} catch (JSONException e) {
e.printStackTrace();
}
Incluye org.json.jsonobject
en tu proyecto.
A continuación, puede hacer esto:
JSONObject jresponse = new JSONObject(responseString);
responseString = jresponse.getString("NeededString");
Asumiendo que responseString
contiene la respuesta que recibes.
Si usted necesita saber cómo convertir la respuesta recibida a una cadena, aquí's cómo hacerlo:
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
String responseString = out.toString();