Подтвердить что ты не робот

Получение значения строки из Json Object Android

Я новичок в 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. Как получить его?

4b9b3361

Ответ 1

Это может помочь вам.

Джава:

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

Ответ 2

Вам просто нужно получить 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();
        }

Ответ 3

Включите org.json.jsonobject в свой проект.

Затем вы можете сделать следующее:

JSONObject jresponse = new JSONObject(responseString);
responseString = jresponse.getString("NeededString");

Предполагая, что responseString содержит полученный вами ответ.

Если вам нужно знать, как преобразовать полученный ответ в строку, вот как это сделать:

ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
String responseString = out.toString();

Ответ 4

Вы можете использовать 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

Ответ 5

Если вы можете использовать JSONObject библиотеку, вы можете просто

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

Ответ 6

Вот код, чтобы получить элемент из 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);
        }

Ответ 7

я думаю, что это полезно для вас

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

                }

Ответ 8

Вот решение, которое я использовал для меня Является ли работа для извлечения 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();
    }