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?


Solution 1:

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.

Solution 2:

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

Solution 3:

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