Я новичок в Android. В мой проект, я получаю следующее JSON из HTTP-ответа.
[{"Date":"2012-1-4T00:00:00",
"keywords":null,
"NeededString":"this is the sample string I am needed for my project",
"others":"not needed"}]
Я хочу попасть в "NeededString" из выше в JSON. Как его получить?
Это может помочь вам.
Для Java:
JSONArray arr = new JSONArray(result);
JSONObject jObj = arr.getJSONObject(0);
String date = jObj.getString("NeededString");
Котлин:
val jsonArray = JSONArray(result)
val jsonObject: JSONObject = jsonArray.getJSONObject(0)
val date= jsonObject.get("NeededString")
Вам просто нужно, чтобы получить JSONArray и перебирать `JSONObject внутри массива, хоть и с помощью цикла в вашем случае его только один JSONObject, но вы можете иметь больше.
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();
}
Вы можете использовать и getString
String name = jsonObject.getString("name");
// it will throws exception if the key you specify doesn't exist
или optString
String name = jsonObject.optString("name");
// it will returns the empty string ("") if the key you specify doesn't exist
Включают орг.в JSON.jsonobject в ваш проект.
Тогда вы можете сделать это:
JSONObject jresponse = new JSONObject(responseString);
responseString = jresponse.getString("NeededString");
Предполагая, `responseString держит ответ вы получите.
Если вам нужно знать, как преобразовать полученный ответ в строку, здесь's, как это сделать:
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
String responseString = out.toString();
<п>вот код , чтобы получить элемент из ResponseEntity <п>
try {
final ResponseEntity<String> responseEntity = restTemplate.exchange(API_URL, HttpMethod.POST, entity, String.class);
log.info("responseEntity"+responseEntity);
final JSONObject jsonObject ;
if (responseEntity.getStatusCode() == HttpStatus.CREATED) {
try {
jsonObject = new JSONObject(responseEntity.getBody());
final String strName = jsonObject.getString("name");
log.info("name:"+strName);
} catch (JSONException e) {
throw new RuntimeException("JSONException occurred");
}
}
}catch (HttpStatusCodeException exception) {
int statusCode = exception.getStatusCode().value();
log.info("statusCode:"+statusCode);
}
Если вы можете использовать [JSONObject] библиотека(http://www.json.org/javadoc/org/json/JSONObject.html), вы могли бы просто
JSONArray ja = new JSONArray("[{\"Date\":\"2012-1-4T00:00:00\",\"keywords\":null,\"NeededString\":\"this is the sample string I am needed for my project\",\"others\":\"not needed\"}]");
String result = ja.getJSONObject(0).getString("NeededString");
Пожалуйста, см. Мой ответ ниже, вдохновленный ответы выше, но немного более подробно...
// Get The Json Response (With Try Catch)
try {
String s = null;
if (response.body() != null) {
s = response.body().string();
// Convert Response Into Json Object (With Try Catch)
JSONObject json = null;
try {
json = new JSONObject(s);
// Extract The User Id From Json Object (With Try Catch)
String stringToExtract = null;
try {
stringToExtract = json.getString("NeededString");
} catch (JSONException e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
я считаю его полезным для вас
JSONArray jre = objJson.getJSONArray("Result");
for (int j = 0; j < jre.length(); j++) {
JSONObject jobject = jre.getJSONObject(j);
String date = jobject.getString("Date");
String keywords=jobject.getString("keywords");
String needed=jobject.getString("NeededString");
}
Вот решение я использовал для меня Это работает для извлечения JSON из строки
protected String getJSONFromString(String stringJSONArray) throws JSONException {
return new StringBuffer(
new JSONArray(stringJSONArray).getJSONObject(0).getString("cartype"))
.append(" ")
.append(
new JSONArray(employeeID).getJSONObject(0).getString("model"))
.toString();
}