[android] Getting String Value from Json Object Android

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?

This question is related to android json parsing

The answer is


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

                }

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

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

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();
    }

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();
        }

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

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

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();
}

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to parsing

Got a NumberFormatException while trying to parse a text file for objects Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) Python/Json:Expecting property name enclosed in double quotes Correctly Parsing JSON in Swift 3 How to get response as String using retrofit without using GSON or any other library in android UIButton action in table view cell "Expected BEGIN_OBJECT but was STRING at line 1 column 1" How to convert an XML file to nice pandas dataframe? How to extract multiple JSON objects from one file? How to sum digits of an integer in java?