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 - Iterate through JSONObject from root in json simple - Stack Overflow
how to iterate through json objects in java - Stack Overflow
java - JSON - Iterate through JSONArray - Stack Overflow
java - how to iterate through this json object and format it - Stack Overflow
Videos
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"));
}
}
You don't have an array - you have properties with names of "000" etc. An array would look like this:
"array": [ {
"foo": "bar1",
"baz": "qux1"
}, {
"foo": "bar2",
"baz": "qux2"
}
]
Note the [ ... ] - that's what indicates a JSON array.
You can iterate through the properties of a JSONObject using keys():
// Unfortunately keys() just returns a raw Iterator...
Iterator keys = jsonObject.keys();
while (keys.hasNext()) {
Object key = keys.next();
JSONObject value = jsonObject.getJSONObject((String) key);
String component = value.getString("component");
System.out.println(component);
}
Or:
@SuppressWarnings("unchecked")
Iterator<String> keys = (Iterator<String>) jsonObject.keys();
while (keys.hasNext()) {
String key = keys.next();
JSONObject value = jsonObject.getJSONObject(key);
String component = value.getString("component");
System.out.println(component);
}
try this...
FileReader file = new FileReader("test.json");
Object obj = parser.parse(file);
System.out.println(obj);
JSONObject jsonObject = (JSONObject) obj;
Iterator<String> iterator = jsonObject .iterator();
for(Iterator iterator = jsonObject.keySet().iterator(); iterator.hasNext();) {
String key = (String) iterator.next();
System.out.println(jsonObject.get(key));
}
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
You can try this it will recursively find all key values in a json object and constructs as a map . You can simply get which key you want from the Map .
public static Map<String,String> parse(JSONObject json , Map<String,String> out) throws JSONException{
Iterator<String> keys = json.keys();
while(keys.hasNext()){
String key = keys.next();
String val = null;
try{
JSONObject value = json.getJSONObject(key);
parse(value,out);
}catch(Exception e){
val = json.getString(key);
}
if(val != null){
out.put(key,val);
}
}
return out;
}
public static void main(String[] args) throws JSONException {
String json = "{'ipinfo': {'ip_address': '131.208.128.15','ip_type': 'Mapped','Location': {'continent': 'north america','latitude': 30.1,'longitude': -81.714,'CountryData': {'country': 'united states','country_code': 'us'},'region': 'southeast','StateData': {'state': 'florida','state_code': 'fl'},'CityData': {'city': 'fleming island','postal_code': '32003','time_zone': -5}}}}";
JSONObject object = new JSONObject(json);
JSONObject info = object.getJSONObject("ipinfo");
Map<String,String> out = new HashMap<String, String>();
parse(info,out);
String latitude = out.get("latitude");
String longitude = out.get("longitude");
String city = out.get("city");
String state = out.get("state");
String country = out.get("country");
String postal = out.get("postal_code");
System.out.println("Latitude : " + latitude + " LongiTude : " + longitude + " City : "+city + " State : "+ state + " Country : "+country+" postal "+postal);
System.out.println("ALL VALUE " + out);
}
Output:
Latitude : 30.1 LongiTude : -81.714 City : fleming island State : florida Country : united states postal 32003
ALL VALUE {region=southeast, ip_type=Mapped, state_code=fl, state=florida, country_code=us, city=fleming island, country=united states, time_zone=-5, ip_address=131.208.128.15, postal_code=32003, continent=north america, longitude=-81.714, latitude=30.1}
How about this?
JSONObject jsonObject = new JSONObject (YOUR_JSON_STRING);
JSONObject ipinfo = jsonObject.getJSONObject ("ipinfo");
String ip_address = ipinfo.getString ("ip_address");
JSONObject location = ipinfo.getJSONObject ("Location");
String latitude = location.getString ("latitude");
System.out.println (latitude);
This sample code using "org.json.JSONObject"
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.