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
*/
Foreach with JSONArray and JSONObject
Apparently, org.json.simple.JSONArray
implements a raw Iterator. This means that each element is considered to be an Object
. You can try to cast:
for(Object o: arr){
if ( o instanceof JSONObject ) {
parse((JSONObject)o);
}
}
This is how things were done back in Java 1.4 and earlier.
How to iterate JSONArray in java
You can use the following code:
//put your json in the string variable "data"
JSONArray jsonArray=new JSONArray(data);
if(jsonArray!=null && jsonArray.length()>0){
for (int i = 0; i < jsonArray.length(); i++) {
JSONArray childJsonArray=jsonArray.optJSONArray(i);
if(childJsonArray!=null && childJsonArray.length()>0){
for (int j = 0; j < childJsonArray.length(); j++) {
System.out.println(childJsonArray.optString(j));
}
}
}
}
Looping through a JSON array in Python
When restaurants
is your list, you have to iterate over this key:
for restaurant in data['restaurants']:
print restaurant['restaurant']['name']
Java loop over Json array?
In your code the element dataArray
is an array of JSON objects, not a JSON object itself. The elements A
, B
, and C
are part of the JSON objects inside the dataArray
JSON array.
You need to iterate over the array
public static void main(String[] args) throws Exception {
String jsonStr = "{ \"dataArray\": [{ \"A\": \"a\", \"B\": \"b\", \"C\": \"c\" }, { \"A\": \"a1\", \"B\": \"b2\", \"C\": \"c3\" }] }";
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray c = jsonObj.getJSONArray("dataArray");
for (int i = 0 ; i < c.length(); i++) {
JSONObject obj = c.getJSONObject(i);
String A = obj.getString("A");
String B = obj.getString("B");
String C = obj.getString("C");
System.out.println(A + " " + B + " " + C);
}
}
prints
a b c
a1 b2 c3
I don't know where msg
is coming from in your code snippet.
How to loop through JSON array and get specific values
in your loop:
for (x in myObj) {
alert(x.car1);
}
x is the string value of key of your object. In order to get the car1 property of your nested object you can change your loop as:
for (x in myObj) {
alert(myObj[x].car1);
}
It is also a good practice to use hasOwnProperty while using for-in
loop it might also iterate over properties which are in your object's prototype chain.
for (x in myObj) {
if (myObj.hasOwnProperty(x)) {
alert(myObj[x].car1);
}
}
Related Topics
How to See Javadoc in Intellij Idea
What Does Inputstream.Available() Do in Java
Java: Difference Between Strong/Soft/Weak/Phantom Reference
Converting String to Date Using Simpledateformat Is Returning Random Date
Intellij: Never Use Wildcard Imports
Jcomponent Stops Getting Rendered Once It Goes Off the Screen
Role/Purpose of Contextloaderlistener in Spring
How to Unit Test Abstract Classes: Extend with Stubs
Transaction Isolation Levels Relation with Locks on Table
Good Examples Using Java.Util.Logging
Intellij - Convert a Java Project/Module into a Maven Project/Module
Java JSON Serialization - Best Practice
Difference Between Using Throwable and Exception in a Try Catch
Put Byte Array to JSON and Vice Versa
Maven Dependency for Servlet 3.0 API
How to Escape Reserved Words in Hibernate's Hql