36

I am beginner in Android. In my Project, I am getting the Following json from the HTTP Response.

[{"Date":"2012-1-4T00:00:00",
"keywords":null,
"NeededString":"this is the sample string I am needed for my project",
"others":"not needed"}]

I want to get the "NeededString" from the above json. How to get it?

DeepBlue
  • 591
  • 9
  • 18
Dray
  • 1,904
  • 5
  • 27
  • 42

9 Answers9

85

This might help you.

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")
  • getJSONObject(index). In above example 0 represents index.
nisha.113a5
  • 2,024
  • 16
  • 30
10

You just need to get the JSONArray and iterate the JSONObject inside the Array using a loop though in your case its only one JSONObject but you may have more.

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();
        }
Lalit Poptani
  • 67,150
  • 23
  • 161
  • 242
6

You can use getString

String name = jsonObject.getString("name");
// it will throws exception if the key you specify doesn't exist

or optString

String name = jsonObject.optString("name");
// it will returns the empty string ("") if the key you specify doesn't exist
Linh
  • 57,942
  • 23
  • 262
  • 279
6

Include org.json.jsonobject in your project.

You can then do this:

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

Assuming, responseString holds the response you receive.

If you need to know how to convert the received response to a String, here's how to do it:

ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
String responseString = out.toString();
Ayush
  • 41,754
  • 51
  • 164
  • 239
2

If you can use JSONObject library, you could just

    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");
Nishant
  • 54,584
  • 13
  • 112
  • 127
1

Here is the code , to get element from 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);
        }
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Nadhu
  • 419
  • 6
  • 5
0

i think its helpfull to you

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

                }
0

Here is the solution I used for me Is works for fetching JSON from string

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();
    }
android.dk
  • 19
  • 1
  • 8
0

Please see my answer below, inspired by answers above but a bit more detailed...

// 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();
}
DragonFire
  • 3,722
  • 2
  • 38
  • 51