Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 948
Dray Avatar asked Jan 04 '12 06:01

Dray


People also ask

How can we access values from JSON object?

A JSONObject has few important methods to display the values of different types like getString() method to get the string associated with a key string, getInt() method to get the int value associated with a key, getDouble() method to get the double value associated with a key and getBoolean() method to get the boolean ...

Can JSON object convert to string?

Stringify a JavaScript ObjectUse the JavaScript function JSON.stringify() to convert it into a string. const myJSON = JSON.stringify(obj); The result will be a string following the JSON notation.

Is JSON string value?

JSON is purely a string with a specified data format — it contains only properties, no methods. JSON requires double quotes to be used around strings and property names. Single quotes are not valid other than surrounding the entire JSON string.

Which method converts a JSON string?

JSON.stringify() The JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.


2 Answers

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.
like image 136
nisha.113a5 Avatar answered Oct 23 '22 10:10

nisha.113a5


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();         } 
like image 21
Lalit Poptani Avatar answered Oct 23 '22 09:10

Lalit Poptani