Dray
Dray

Reputation: 1954

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?

Upvotes: 36

Views: 163584

Answers (9)

nisha.113a5
nisha.113a5

Reputation: 2024

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.

Upvotes: 85

DragonFire
DragonFire

Reputation: 4082

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

Upvotes: 0

Nadhu
Nadhu

Reputation: 429

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

Upvotes: 1

Nilesh mayatra
Nilesh mayatra

Reputation: 1

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

                }

Upvotes: 0

Linh
Linh

Reputation: 60923

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

Upvotes: 6

android.dk
android.dk

Reputation: 19

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

Upvotes: 0

Nishant
Nishant

Reputation: 55866

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

Upvotes: 2

Lalit Poptani
Lalit Poptani

Reputation: 67286

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

Upvotes: 10

Ayush
Ayush

Reputation: 42450

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

Upvotes: 6

Related Questions