Here you get JSONObject so change this line:

JSONArray jsonArray = new JSONArray(readlocationFeed); 

with following:

JSONObject jsnobject = new JSONObject(readlocationFeed);

and after

JSONArray jsonArray = jsnobject.getJSONArray("locations");
for (int i = 0; i < jsonArray.length(); i++) {
    JSONObject explrObject = jsonArray.getJSONObject(i);
}
Answer from kyogs on Stack Overflow
🌐
TutorialsPoint
tutorialspoint.com › how-to-read-parse-json-array-using-java
How to read/parse JSON array using Java?
May 5, 2025 - import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.Iterator; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; public class ReadingArrayFromJSON { public static void main(String args[]) { //Creating a JSONParser object JSONParser jsonParser = new JSONParser(); try { //Parsing the contents of the JSON file JSONObject jsonObject = (JSONObject) jsonParser.parse(new FileReader("E:/test.json")); //Forming URL System.out.println("Conten
🌐
Mkyong
mkyong.com › home › java › how to parse json array with jackson
How to parse JSON Array with Jackson - Mkyong.com
April 23, 2024 - package com.mkyong.json.jackson; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.mkyong.json.model.Person; import java.util.Arrays; import java.util.List; public class JsonArrayToObjectExample2 { public static void main(String[] args) throws JsonProcessingException { List<Person> list = Arrays.asList( new Person("mkyong", 42), new Person("ah pig", 20) ); ObjectMapper mapper = new ObjectMapper(); String result = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(list); System.out.println(result); } }
Discussions

java - Convert string to JSON array - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work More on stackoverflow.com
🌐 stackoverflow.com
java - parse string array from JSON - Stack Overflow
Should be "recipients" instead of "name" therefore. 2015-07-15T08:25:49.767Z+00:00 ... You can try to use xstream with json serializer. Take a look this link ... I always suggest my favorite library json-lib to handle JSON stuffs. You can use JSONArray to convert to Object[], although it's not String[], you can still use it because every Object has toString() method. String sYourJsonString = "['u3848', 'u8958', 'u7477474']"; Object[] arrayReceipients ... More on stackoverflow.com
🌐 stackoverflow.com
June 13, 2012
parsing - How to parse this jsonarray to string or array java - Stack Overflow
Type "Java JSON parsing" into your favorite search engine. ... String arr[] = {"black-chest-close.png","diamond-chest-close.png","gold-chest-close.png", "logo.png","logo1.png","ruby-chest-close.png","sapphire-chest-close.png"}; ... JSONArray arr = new JSONArray(yourJSONresponse); List list = new ArrayList... More on stackoverflow.com
🌐 stackoverflow.com
Java - Parse JSON Array of Strings into String Array - Stack Overflow
Above is a snippet of the JSON file I am working with for a text based game I am making in Java. I was able to parse thorough a different file that did not have another array in each location (the objects and directions), but this one does have an array and I am quite stuck. I need the objects to be added to an array of strings ... More on stackoverflow.com
🌐 stackoverflow.com
November 21, 2019
🌐
Crunchify
crunchify.com › json tutorials › how to parse jsonobject and jsonarrays in java? beginner’s guide
How to Parse JSONObject and JSONArrays in Java? Beginner's Guide • Crunchify
February 2, 2023 - Here is a complete Java program that demonstrates parsing both JSON objects and arrays. package crunchify.com.java.tutorials; import org.json.JSONArray; import org.json.JSONObject; /** * @author Crunchify.com * Program: How to Parse JSONObject and JSONArrays in Java? Beginner's Guide * */ public class CrunchifyParseJsonObjectAndArray { public static void main(String[] args) { // JSON object string String jsonObjectString = "{\"name\":\"Crunchify\",\"year\":2023,\"city\":\"New York\"}"; // Parse the JSON object string into a JSONObject JSONObject jsonObject = new JSONObject(jsonObjectString); /
🌐
Blogger
javarevisited.blogspot.com › 2013 › 04 › convert-json-array-to-string-array-list-java-from.html
How to Convert JSON array to String array in Java - GSon example
In this tutorial, we will use GSON to parse the JSON data format and create a Java String array or List from JSON array representation.
🌐
Mkyong
mkyong.com › home › java › how to parse json array using gson
How to parse JSON Array using Gson - Mkyong.com
May 17, 2024 - The following example uses Gson to convert a JSON array to the List<Item>. ... package com.mkyong.json.gson; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.mkyong.json.gson.model.Item; import java.lang.reflect.Type; import java.util.List; public class GsonParseJsonArrayExample1 { public static void main(String[] args) { String json = """ [ { "id": 1, "name": "a" }, { "id": 2, "name": "b" } ] """; Gson gson = new Gson(); // create a List<Item> Type listItemType = new TypeToken<List<Item>>() {}.getType(); // convert json array to List<Item> List<Item> list = gson.fromJson(json, listItemType); list.forEach(System.out::println); } }
🌐
Stack Overflow
stackoverflow.com › questions › 50597099 › how-to-parse-this-jsonarray-to-string-or-array-java
parsing - How to parse this jsonarray to string or array java - Stack Overflow
Type "Java JSON parsing" into your favorite search engine. ... String arr[] = {"black-chest-close.png","diamond-chest-close.png","gold-chest-close.png", "logo.png","logo1.png","ruby-chest-close.png","sapphire-chest-close.png"}; ... JSONArray arr = new JSONArray(yourJSONresponse); List<String> list = new ArrayList<String>(); for(int i = 0; i < arr.length(); i++){ list.add(arr.getJSONObject(i).getString("name")); }
Find elsewhere
🌐
HowToDoInJava
howtodoinjava.com › home › gson › gson – parse json array to java array or list
Gson - Parse JSON Array to Java Array or List
April 4, 2023 - Learn to use Google GSON library to deserialize or convert JSON, containing JSON array as root or member, to Java Array or List of objects.
Top answer
1 of 2
1

So I ended up getting it to work with these changes! I had never worked with JSON before this project and apparently I had it written wrong for what I was trying to do.

        JSONParser jsonParser2 = new JSONParser();
        try (FileReader reader = new FileReader("Locations.json")) {
            Object obj = jsonParser2.parse(reader);

            JSONArray locationsList = (JSONArray) obj;

            //Iterate over locations array
            locationsList.forEach(emp -> parseJSONLocations((JSONObject) emp, locations, objects));

        } catch (FileNotFoundException e) {
            System.out.println(e);
        } catch (IOException | ParseException e) {
            System.out.println(e);
        }

and then the method to add it all to a class was changed as such:

    private static void parseJSONLocations(JSONObject locations, Locations[] location, Objects[] object) {
        JSONObject locationObject = (JSONObject) locations.get("locations");
        String desc = (String) locationObject.get("description");
        String name = (String) locationObject.get("name");
        JSONArray objects = (JSONArray) locationObject.get("objects");

        Iterator<String> it = objects.iterator();
        List<Objects> objs = new ArrayList<>();
        while (it.hasNext()) {
            String mStr = it.next();
            for (Objects elm : object) {
                if (elm.getName().equals(mStr)) {
                    objs.add(elm);
                }
            }
        }

        JSONArray directions = (JSONArray) locationObject.get("directions");
        Map<String, String> map = new HashMap<>();
        Iterator<JSONObject> it2 = directions.iterator();
        while (it2.hasNext()) {
            JSONObject value = it2.next();
            map.put((String) value.get("direction"), (String) value.get("location"));
        }
        location[index2] = new Locations(desc, name, objs, map);
        index2++;
    }

But then I also had to change my JSON code, per jgolebiewski's suggestion:

[
    {
        "locations": {
            "description": "You look around the room and see you are in an empty room with 2 doors to the left and to the right. Knowing not how you got there, you decide to figure out how to escape and get back to your normal life.",
            "name": "start",
            "objects": [],
            "directions": [{
                    "direction": "right",
                    "location": "empty room1"
                }, {
                    "direction": "left",
                    "location": "dungeon"
                }]
        }
    },
    {
        "locations": {
            "description": "Inside this room it looks like some sort of dungeon with a cage in the middle and blood lining the wall and floor.",
            "name": "dungeon",
            "objects": ["map", "torch"],
            "directions": [{
                    "direction": "up",
                    "location": "hallway2"
                }, {
                    "direction": "down",
                    "location": "hallway1"
                }, {
                    "direction": "right",
                    "location": "start"
                }]
        }
    }
]

Thank you for this tutorial for helping as well: https://howtodoinjava.com/library/json-simple-read-write-json-examples/

2 of 2
1

I am not sure what library you're using for json mapping, but i can give you some advices, which may help:

  • when mapping objects property try to map it to List<String> instead of String[]
  • changing directions property may help to map it to Map object:

try to change this: "directions": [{"right":"empty room1"}, {"left":"dungeon"}]

to this: "directions": {"right":"empty room1", "left":"dungeon"}

Top answer
1 of 3
58

for your example:

{'profiles': [{'name':'john', 'age': 44}, {'name':'Alex','age':11}]}

you will have to do something of this effect:

JSONObject myjson = new JSONObject(the_json);
JSONArray the_json_array = myjson.getJSONArray("profiles");

this returns the array object.

Then iterating will be as follows:

    int size = the_json_array.length();
    ArrayList<JSONObject> arrays = new ArrayList<JSONObject>();
    for (int i = 0; i < size; i++) {
        JSONObject another_json_object = the_json_array.getJSONObject(i);
            //Blah blah blah...
            arrays.add(another_json_object);
    }

//Finally
JSONObject[] jsons = new JSONObject[arrays.size()];
arrays.toArray(jsons);

//The end...

You will have to determine if the data is an array (simply checking that charAt(0) starts with [ character).

Hope this helps.

2 of 3
1

You can prefer quick-json parser to meet your requirement...

quick-json parser is very straight forward, flexible, very fast and customizable. Try this out

[quick-json parser] (https://code.google.com/p/quick-json/) - quick-json features -

  • Compliant with JSON specification (RFC4627)

  • High-Performance JSON parser

  • Supports Flexible/Configurable parsing approach

  • Configurable validation of key/value pairs of any JSON Heirarchy

  • Easy to use # Very Less foot print

  • Raises developer friendly and easy to trace exceptions

  • Pluggable Custom Validation support - Keys/Values can be validated by configuring custom validators as and when encountered

  • Validating and Non-Validating parser support

  • Support for two types of configuration (JSON/XML) for using quick-json validating parser

  • Require JDK 1.5 # No dependency on external libraries

  • Support for Json Generation through object serialization

  • Support for collection type selection during parsing process

For e.g.

JsonParserFactory factory=JsonParserFactory.getInstance();
JSONParser parser=factory.newJsonParser();
Map jsonMap=parser.parseJson(jsonString);
🌐
Stack Overflow
stackoverflow.com › questions › 11555894 › parsing-json-array
java - Parsing JSON ARRAY - Stack Overflow
I don't know how to get "idMembers" ! Any idea, because it's array in a array? JSONArray msg2 = (JSONArray) all.get("cards"); then · for (int i2 = 0; i2 < size2; i2++) { myobject = (JSONObject) msg2.get(i2); listTemp2.add(jsonObecjtToMyData(myobject)); } String boardName = (String) monobjet.get("name"); java ·
🌐
Delft Stack
delftstack.com › home › howto › java › parse json in java
How to Parse JSON in Java | Delft Stack
February 2, 2024 - We have to import two classes from java.simple library, org.json.simple.JSONArray and org.json.simple.JSONObject. The JSONArray helps us parse elements in the form of an array, and the JSONObject allows us to parse the objects present in the ...
Top answer
1 of 7
100

See my comment. You need to include the full org.json library when running as android.jar only contains stubs to compile against.

In addition, you must remove the two instances of extra } in your JSON data following longitude.

   private final static String JSON_DATA =
     "{" 
   + "  \"geodata\": [" 
   + "    {" 
   + "      \"id\": \"1\"," 
   + "      \"name\": \"Julie Sherman\","                  
   + "      \"gender\" : \"female\"," 
   + "      \"latitude\" : \"37.33774833333334\"," 
   + "      \"longitude\" : \"-121.88670166666667\""
   + "    }," 
   + "    {" 
   + "      \"id\": \"2\"," 
   + "      \"name\": \"Johnny Depp\","          
   + "      \"gender\" : \"male\"," 
   + "      \"latitude\" : \"37.336453\"," 
   + "      \"longitude\" : \"-121.884985\""
   + "    }" 
   + "  ]" 
   + "}"; 

Apart from that, geodata is in fact not a JSONObject but a JSONArray.

Here is the fully working and tested corrected code:

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class ShowActivity {


  private final static String JSON_DATA =
     "{" 
   + "  \"geodata\": [" 
   + "    {" 
   + "      \"id\": \"1\"," 
   + "      \"name\": \"Julie Sherman\","                  
   + "      \"gender\" : \"female\"," 
   + "      \"latitude\" : \"37.33774833333334\"," 
   + "      \"longitude\" : \"-121.88670166666667\""
   + "    }," 
   + "    {" 
   + "      \"id\": \"2\"," 
   + "      \"name\": \"Johnny Depp\","          
   + "      \"gender\" : \"male\"," 
   + "      \"latitude\" : \"37.336453\"," 
   + "      \"longitude\" : \"-121.884985\""
   + "    }" 
   + "  ]" 
   + "}"; 

  public static void main(final String[] argv) throws JSONException {
    final JSONObject obj = new JSONObject(JSON_DATA);
    final JSONArray geodata = obj.getJSONArray("geodata");
    final int n = geodata.length();
    for (int i = 0; i < n; ++i) {
      final JSONObject person = geodata.getJSONObject(i);
      System.out.println(person.getInt("id"));
      System.out.println(person.getString("name"));
      System.out.println(person.getString("gender"));
      System.out.println(person.getDouble("latitude"));
      System.out.println(person.getDouble("longitude"));
    }
  }
}

Here's the output:

C:\dev\scrap>java -cp json.jar;. ShowActivity
1
Julie Sherman
female
37.33774833333334
-121.88670166666667
2
Johnny Depp
male
37.336453
-121.884985
2 of 7
6

To convert your JSON string to hashmap you can make use of this :

HashMap<String, Object> hashMap = new HashMap<>(Utility.jsonToMap(response)) ;

Use this class :) (handles even lists , nested lists and json)

public class Utility {

    public static Map<String, Object> jsonToMap(Object json) throws JSONException {

        if(json instanceof JSONObject)
            return _jsonToMap_((JSONObject)json) ;

        else if (json instanceof String)
        {
            JSONObject jsonObject = new JSONObject((String)json) ;
            return _jsonToMap_(jsonObject) ;
        }
        return null ;
    }


   private static Map<String, Object> _jsonToMap_(JSONObject json) throws JSONException {
        Map<String, Object> retMap = new HashMap<String, Object>();

        if(json != JSONObject.NULL) {
            retMap = toMap(json);
        }
        return retMap;
    }


    private static Map<String, Object> toMap(JSONObject object) throws JSONException {
        Map<String, Object> map = new HashMap<String, Object>();

        Iterator<String> keysItr = object.keys();
        while(keysItr.hasNext()) {
            String key = keysItr.next();
            Object value = object.get(key);

            if(value instanceof JSONArray) {
                value = toList((JSONArray) value);
            }

            else if(value instanceof JSONObject) {
                value = toMap((JSONObject) value);
            }
            map.put(key, value);
        }
        return map;
    }


    public static List<Object> toList(JSONArray array) throws JSONException {
        List<Object> list = new ArrayList<Object>();
        for(int i = 0; i < array.length(); i++) {
            Object value = array.get(i);
            if(value instanceof JSONArray) {
                value = toList((JSONArray) value);
            }

            else if(value instanceof JSONObject) {
                value = toMap((JSONObject) value);
            }
            list.add(value);
        }
        return list;
    }
}

🌐
Reddit
reddit.com › r/javahelp › using jsonarray, jsonobject etc. to parse json with java
r/javahelp on Reddit: using JSONArray, JSONObject etc. to parse JSON with Java
May 22, 2022 -

Hi,

I am reading json into a Java program, where I am attempting to process it. I'm having some challenges figuring out how to dig down into the data structure, in order to iterate through some of the deeper lists. I'm attaching below excerpts of the Java, and the toy/test json.

Here is the toy/test json:

{
    "objects": [
        {
            "type": "object-1",
            "coordinates": [
                [
                    0,
                    5
                ],
                [
                    5,
                    10
                ],
                [
                    10,
                    15
                ],
                [
                    15,
                    0
                ]
            ]
        }
    ]
}

What I WANT to do is grab the list of objects associated with the key "objects", and then iterate through the dictionaries that compose the list, further extracting components (coordinates, say, if the type is what i'm after).

The thing is, I don't know how to do this. The code below is an attempt, but it doesn't work.

Here's the Java excerpt:

JSONObject json;

void setup() {
  
  size(800, 494);
  
  // input json file
  String inputJsonFile = "input.json";
  String inputJsonFileContentsString = "";
  
  try { 
      inputJsonFileContentsString = readFileIntoString( inputJsonFile );
  }
  catch (IOException e) {
      e.printStackTrace();
  }
  
  //JSON parser object to parse read file
  JSONObject inputJsonData = parseJSONObject( inputJsonFileContentsString );
  
  // recover list of objects
  JSONArray objects = inputJsonData.getJSONArray( "objects" );
  
  // print json data: iterate over list of objects, retrieving type and coordinates
  int arrayLength = objects.size();
  for ( int i = 0; i < arrayLength; i++ ) {

    // THIS DOESN'T WORK
    // I want the next dictionary/hash, but how to retrieve it?
    JSONObject objectDataHash = objects[ i ];
    
  }
  
}

Thank you. I normally work with Python, it's been a while since I've done a lot of coding in Java so I'm probably missing something obvious.

🌐
Stack Overflow
stackoverflow.com › questions › 68435655 › parse-a-json-string-to-an-array-using-jackson
java - Parse a JSON string to an array using Jackson - Stack Overflow
package JsonToJava.test; import java.io.File; import java.io.IOException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; public class JsontoJava { public static void main( String[] args ) throws JsonMappingException, JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); try { Data[] dataObj = mapper.readValue(new File("data/sample_array_data.json"), Data[].class); for (Data data: dataObj) { System.out.println("Track Name--->"+data.getName()); System.out.println("Printing Elements--->"+data.getElements()); System.out.println("------------------------"); } } catch (JsonMappingException e) { e.printStackTrace(); }catch (JsonProcessingException e) { e.printStackTrace(); }catch (IOException e) { e.printStackTrace(); } } }