JSON Array iteration in Android/Java
I have done it two different ways,
1.) make a Map
HashMap<String, String> applicationSettings = new HashMap<String,String>();
for(int i=0; i<settings.length(); i++){
String value = settings.getJSONObject(i).getString("value");
String name = settings.getJSONObject(i).getString("name");
applicationSettings.put(name, value);
}
2.) make a JSONArray of names
JSONArray names = json.names();
JSONArray values = json.toJSONArray(names);
for(int i=0; i<values.length(); i++){
if (names.getString(i).equals("description")){
setDescription(values.getString(i));
}
else if (names.getString(i).equals("expiryDate")){
String dateString = values.getString(i);
setExpiryDate(stringToDateHelper(dateString));
}
else if (names.getString(i).equals("id")){
setId(values.getLong(i));
}
else if (names.getString(i).equals("offerCode")){
setOfferCode(values.getString(i));
}
else if (names.getString(i).equals("startDate")){
String dateString = values.getString(i);
setStartDate(stringToDateHelper(dateString));
}
else if (names.getString(i).equals("title")){
setTitle(values.getString(i));
}
}
Android - Loop on JsonArray?
Your Response Should be like that Have A look to response is like my answer
[{
"X": "54.6000621",
"Y": "45.8360411",
"Dates": [{
"Date": "2000\/04\/26",
"Time": "12:13:45"
}, {
"Date": "2000\/04\/26",
"Time": "13:13:45"
}, {
"Date": "2000\/04\/26",
"Time": "14:13:12"
}, {
"Date": "2000\/04\/26",
"Time": "15:13:10"
}, {
"Date": "2000\/04\/26",
"Time": "16:13:48"
}],
"Count": 5
},
{
"X": "98.6254621",
"Y": "99.8360411",
"Dates": [{
"Date": "2012\/04\/26",
"Time": "12:13:45"
}, {
"Date": "2012\/04\/26",
"Time": "13:13:45"
}, {
"Date": "2012\/04\/26",
"Time": "14:13:12"
}, {
"Date": "2012\/04\/26",
"Time": "15:13:10"
}, {
"Date": "2012\/04\/26",
"Time": "16:13:48"
}, {
"Date": "2012\/04\/26",
"Time": "15:13:10"
}, {
"Date": "2012\/04\/26",
"Time": "15:13:10"
}],
"Count": 7
},
{
"X": "58.4582621",
"Y": "85.8360411",
"Dates": [],
"Count": 0
}]
Code to Take Value
try {
JSONArray jsonArray=new JSONArray(response);
for (int i=0;i<jsonArray.length();i++)
{
JSONObject jsonObject=jsonArray.getJSONObject(i);
String X=jsonObject.getString("X");
String Y=jsonObject.getString("Y");
String Count=jsonObject.getString("Count");
JSONArray jsonArraydates=jsonObject.getJSONArray("Dates");
for (int j=0;j<jsonArraydates.length();j++)
{
JSONObject jsonObjectDates=jsonArraydates.getJSONObject(j);
String Date=jsonObjectDates.getString("Date");
String Time=jsonObjectDates.getString("Time");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
How can I loop over a json array in android?
Traverse the JsonArray
using size
while fetching the JsonElement
using get
function using i
index and convert it into JsonObject
using getAsJsonObject()
function
JsonParser parser = new JsonParser();
JsonElement notes = parser.parse(s);
JsonArray notesArr = notes.getAsJsonArray();
for (int i = 0; i < notesArr.size(); i++) {
// get your jsonobject
JsonObject obj = notesArr.get(i).getAsJsonObject();
// do the same for the rest of the elements like date , author ,authorId
String id,noteText,author;
// fetch data from object
id = obj.get("id").getAsString();
noteText = obj.get("noteText").getAsString();
author = obj.get("author").getAsString();
// Store these values in list or objects you want
System.out.println(id);
System.out.println(noteText);
System.out.println(author);
}
output :
0
NotJSON Array iteration in Android/Java Android - Loop on JsonArray? How can I loop over a json array in android? How to loop through JSONArray inside JSONObject How to cr
John
1
NotJSON Array iteration in Android/Java Android - Loop on JsonArray? How can I loop over a json array in android? How to loop through JSONArray inside JSONObject How to cr
Rob
How to loop through JSONArray inside JSONObject
Something like this.
// Get a reference to the JSON object
JSONObject jSONObject = new JSONObject(stringJsonResponse);
// Getting the JSON array node
JSONArray jsonAray = jSONObject.getJSONArray("Apps");
// Looping through the json array
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject childrenObject = childrenArray.getJSONObject(i);
...
...
...
}
You can take a look at how I parsed JSON data when I received similar data https://github.com/gSrikar/AskReddit/blob/master/app/src/main/java/com/example/srikar/askreddit/MainActivity.java
How to create JSON Array with Loop Data in Android
JSONArray jsa = new JSONArray();
for (int i = 1; i<= 20; i++) {
JSONObject cust = new JSONObject();
cust.put("number",String.valueOf(i));
cust.put("name","customer"+i);
cust.put("url","url"+i);
jsa.put(cust);
}
System.out.println(jsa.toString());
json response iteration android studio/retrofit
In your provided JSON hierarchy photo the name of the root element doesn't appear, so I assumed it as "root_element" in below script
- Here the entire JSON response can be read as a
JSONObject
. - And as this
JSONObject
has multiple elements in it (in picture
named as 0, 1, 2..); then you can get aJSONArray
usinggetJSONArray()
method. - Then you can loop through this
JSONArray
to get a paricular element from the (0, 1, 2...) - After that you can another
JSONObject
from this particular element which isowner
in your JSON structure photo. - And finally you can read Strings of this owner using
getString()
String jsonResponse = ""; // Put the entire JSON response as a String
JSONObject root = new JSONObject(jsonResponse); // jsonResponse is the entire JSON string
JSONArray rootArray = root.getJSONArray("root_element"); // your root element is not show in your provided photo
for (int i = 0; i < rootArray.length(); i++) {
JSONObject element = rootArray.getJSONObject(i);
JSONObject owner = element.getJSONObject("owner");
String email = owner.getString("email");
String givenName = owner.getString("givenName");
String id = owner.getString("id");
String lastName = owner.getString("lastName");
String realm = owner.getString("realm");
String userName = owner.getString("userName");
}
JSON - Iterate through JSONArray
Change
JSONObject objects = getArray.getJSONArray(i);
to
JSONObject objects = getArray.getJSONObject(i);
or to
JSONObject objects = getArray.optJSONObject(i);
depending on which JSON-to/from-Java library you're using. (It looks like getJSONObject
will work for you.)
Then, to access the string elements in the "objects" JSONObject
, get them out by element name.
String a = objects.get("A");
If you need the names of the elements in the JSONObject
, you can use the static utility method JSONObject.getNames(JSONObject)
to do so.
String[] elementNames = JSONObject.getNames(objects);
"Get the value for the first element and the value for the last element."
If "element" is referring to the component in the array, note that the first component is at index 0, and the last component is at index getArray.length() - 1
.
I want to iterate though the objects in the array and get thier component and thier value. In my example the first object has 3 components, the scond has 5 and the third has 4 components. I want iterate though each of them and get thier component name and value.
The following code does exactly that.
import org.json.JSONArray;
import org.json.JSONObject;
public class Foo
{
public static void main(String[] args) throws Exception
{
String jsonInput = "{\"JObjects\":{\"JArray1\":[{\"A\":\"a\",\"B\":\"b\",\"C\":\"c\"},{\"A\":\"a1\",\"B\":\"b2\",\"C\":\"c3\",\"D\":\"d4\",\"E\":\"e5\"},{\"A\":\"aa\",\"B\":\"bb\",\"C\":\"cc\",\"D\":\"dd\"}]}}";
// "I want to iterate though the objects in the array..."
JSONObject outerObject = new JSONObject(jsonInput);
JSONObject innerObject = outerObject.getJSONObject("JObjects");
JSONArray jsonArray = innerObject.getJSONArray("JArray1");
for (int i = 0, size = jsonArray.length(); i < size; i++)
{
JSONObject objectInArray = jsonArray.getJSONObject(i);
// "...and get thier component and thier value."
String[] elementNames = JSONObject.getNames(objectInArray);
System.out.printf("%d ELEMENTS IN CURRENT OBJECT:\n", elementNames.length);
for (String elementName : elementNames)
{
String value = objectInArray.getString(elementName);
System.out.printf("name=%s, value=%s\n", elementName, value);
}
System.out.println();
}
}
}
/*
OUTPUT:
3 ELEMENTS IN CURRENT OBJECT:
name=A, value=a
name=B, value=b
name=C, value=c
5 ELEMENTS IN CURRENT OBJECT:
name=D, value=d4
name=E, value=e5
name=A, value=a1
name=B, value=b2
name=C, value=c3
4 ELEMENTS IN CURRENT OBJECT:
name=D, value=dd
name=A, value=aa
name=B, value=bb
name=C, value=cc
*/
Related Topics
Convert Word Doc to HTML Programmatically in Java
Gson Throwing "Expected Begin_Object But Was Begin_Array"
Java Using Much More Memory Than Heap Size (Or Size Correctly Docker Memory Limit)
Is Java "Pass-By-Reference" or "Pass-By-Value"
What's Wrong With Java Date & Time API
How to Load Jar Files Dynamically At Runtime
Why Doesn't Java Allow Overriding of Static Methods
Error - Trustanchors Parameter Must Be Non-Empty
Example Images For Code and Mark-Up Q&As
Update Eclipse With Android Development Tools V. 23
How to Request Location Permission At Runtime
Error: Could Not Find or Load Main Class
Scanner Is Skipping Nextline() After Using Next() or Nextfoo()
When to Use Linkedlist Over Arraylist in Java