I have a JSON file with some arrays in it. I want to iterate through the file arrays and get their elements and their values.
This is how my file looks like:
{
"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"
}
]
}
}
This is how far I have come:
JSONObject object = new JSONObject("json-file.json");
JSONObject getObject = object.getJSONObject("JObjects");
JSONArray getArray = getObject.getJSONArray("JArray1");
for(int i = 0; i < getArray.length(); i++)
{
JSONObject objects = getArray.getJSONArray(i);
//Iterate through the elements of the array i.
//Get thier value.
//Get the value for the first element and the value for the last element.
}
Is it possible to do something like this?
The reason I want to do it like this is because the arrays in the file have a different number of elements.
Change
to
or to
depending on which JSON-to/from-Java library you’re using. (It looks like
getJSONObjectwill work for you.)Then, to access the string elements in the “objects”
JSONObject, get them out by element name.If you need the names of the elements in the
JSONObject, you can use the static utility methodJSONObject.getNames(JSONObject)to do so.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.The following code does exactly that.