Maybe this will help:
JSONObject jsonObject = new JSONObject(contents.trim());
Iterator<String> keys = jsonObject.keys();
while(keys.hasNext()) {
String key = keys.next();
if (jsonObject.get(key) instanceof JSONObject) {
// do something with jsonObject here
}
}
Answer from Rickey on Stack OverflowMaybe this will help:
JSONObject jsonObject = new JSONObject(contents.trim());
Iterator<String> keys = jsonObject.keys();
while(keys.hasNext()) {
String key = keys.next();
if (jsonObject.get(key) instanceof JSONObject) {
// do something with jsonObject here
}
}
for my case i found iterating the names() works well
for(int i = 0; i<jobject.names().length(); i++){
Log.v(TAG, "key = " + jobject.names().getString(i) + " value = " + jobject.get(jobject.names().getString(i)));
}
java - Foreach with JSONArray and JSONObject - Stack Overflow
java - Iterate through JSONObject from root in json simple - Stack Overflow
java - how to iterate through this json object and format it - Stack Overflow
java - JSON - Iterate through JSONArray - Stack Overflow
Seems like you can't iterate through JSONArray with a for each. You can loop through your JSONArray like this:
for (int i=0; i < arr.length(); i++) {
arr.getJSONObject(i);
}
Source
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.
Assuming your JSON object is saved in a file "simple.json", you can iterate over the attribute-value pairs as follows:
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("simple.json"));
JSONObject jsonObject = (JSONObject) obj;
for(Iterator iterator = jsonObject.keySet().iterator(); iterator.hasNext();) {
String key = (String) iterator.next();
System.out.println(jsonObject.get(key));
}
You can do like this
String jsonstring = "{ \"child\": { \"something\": \"value\", \"something2\": \"value\" } }";
JSONObject resobj = new JSONObject(jsonstring);
Iterator<?> keys = resobj.keys().iterator();
while(keys.hasNext() ) {
String key = (String)keys.next();
if ( resobj.get(key) instanceof JSONObject ) {
JSONObject xx = new JSONObject(resobj.get(key).toString());
Log.d("res1",xx.getString("something"));
Log.d("res2",xx.getString("something2"));
}
}
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
*/
for (int i = 0; i < getArray.length(); i++) {
JSONObject objects = getArray.getJSONObject(i);
Iterator key = objects.keys();
while (key.hasNext()) {
String k = key.next().toString();
System.out.println("Key : " + k + ", value : "
+ objects.getString(k));
}
// System.out.println(objects.toString());
System.out.println("-----------");
}
Hope this helps someone
I have a JSON response that will be set up like this:
JSON:
{
"lines": [
{
"currencyTypeName": "Mirror of Kalandra",
"pay": {
"id": 0,
"league_id": 1,
"pay_currency_id": 22,
"get_currency_id": 1,
"sample_time_utc": "2023-04-16T00:34:10.2107897Z",
"count": 106,
"value": 0.00000910000000,
"data_point_count": 1,
"includes_secondary": true,
"listing_count": 1155
},
"receive": {
"id": 0,
"league_id": 1,
"pay_currency_id": 1,
"get_currency_id": 22,
"sample_time_utc": "2023-04-16T00:34:10.2107897Z",
"count": 44,
"value": 122100.00000000000000,
"data_point_count": 1,
"includes_secondary": true,
"listing_count": 190
},
"paySparkLine": {
"data": [
0,
0,
0,
0,
0,
0,
9.89
],
"totalChange": 9.89
},
"receiveSparkLine": {
"data": [
0,
-3.05,
-3.98,
-4.40,
-6.81,
-7.61,
-8.85
],
"totalChange": -8.85
},
"chaosEquivalent": 113471.68,
"lowConfidencePaySparkLine": {
"data": [
0,
0,
0,
0,
0,
0,
9.89
],
"totalChange": 9.89
},
"lowConfidenceReceiveSparkLine": {
"data": [
0,
-3.05,
-3.98,
-4.40,
-6.81,
-7.61,
-8.85
],
"totalChange": -8.85
},
"detailsId": "mirror-of-kalandra"
},
{
"currencyTypeName": "Mirror Shard",
"pay": {
"id": 0,
"league_id": 1,
"pay_currency_id": 81,
"get_currency_id": 1,
"sample_time_utc": "2023-04-16T00:34:10.2107897Z",
"count": 22,
"value": 0.00018520000000,
"data_point_count": 1,
"includes_secondary": true,
"listing_count": 50
},
"receive": {
"id": 0,
"league_id": 1,
"pay_currency_id": 1,
"get_currency_id": 81,
"sample_time_utc": "2023-04-16T00:34:10.2107897Z",
"count": 37,
"value": 6398.04000000000000,
"data_point_count": 1,
"includes_secondary": true,
"listing_count": 273
},
"paySparkLine": {
"data": [
0,
0,
0,
0,
0,
0,
2.59
],
"totalChange": 2.59
},
"receiveSparkLine": {
"data": [
0,
-1.79,
-2.13,
-2.55,
-4.26,
-4.52,
-6.12
],
"totalChange": -6.12
},
"chaosEquivalent": 6025.73,
"lowConfidencePaySparkLine": {
"data": [
0,
0,
0,
0,
0,
0,
2.59
],
"totalChange": 2.59
},
"lowConfidenceReceiveSparkLine": {
"data": [
0,
-1.79,
-2.13,
-2.55,
-4.26,
-4.52,
-6.12
],
"totalChange": -6.12
},
"detailsId": "mirror-shard"
}
]
}Using Gson, I am parsing the JSON response from a server into a POJO using the below method:
POJO:
public class Currency {
@SerializedName("chaosEquivalent")
private Double chaosEquivalent;
@SerializedName("currencyTypeName")
private String currencyName;
@SerializedName("detailsId")
private String detailsId;
//Getters and setters
}Gson code:
public List<Currency> getCurrency ( String league, String localization, boolean update ) throws IOException {
if ( currency == null || update) {
String url = "https://poe.ninja/api/data/currencyoverview?league=" + league + "&type=Currency" + "&language=" + localization;
currency = new ArrayList<> ( );
Gson gson = new Gson ();
InputStreamReader in = new InputStreamReader ( new URL ( url ).openStream () );
JsonReader reader = new JsonReader ( in );
reader.beginObject ();
reader.nextName ();
currency = gson.fromJson ( reader, new TypeToken<List<Currency>> () {}.getType () );
reader.close ();
}
return currency;
}The issue:
The above Gson code works if I want to parse the entirety of the JSON response. Instead of the entirety of the response, I only want to parse what I need to via stream until I identify the item I'm looking for.
For example:
while ( reader.hasNext () ) {
/*
* What do I need to do before this line?
*/
Currency c = gson.fromJson ( reader, Currency.class );
if ( c.name().equals ( "nameofobjectlookingfor" ) ) {
//Do stuff that I need to do.
}
}However, I seem to not be able to do the above in one way or another. I always get errors stating BEGIN_ARRAY expected but was STRING, or BEGIN_OBJECT. I still want to map the JSON to the POJO, but I am struggling to find the solution. Essentially, I want to map objects one at a time instead of bulk.
Is this a possibility? Examples online show utilizing the peek() method and comparing tokens, but that seems to send me down the road of manually mapping every object through if statements when I believe I should be able to just map via the Gson class.