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
🌐
GeeksforGeeks
geeksforgeeks.org › java › how-to-convert-json-array-to-string-array-in-java
How to Convert JSON Array to String Array in Java? - GeeksforGeeks
July 23, 2025 - This is being done here because when we will convert it into a String array, we want to ensure that there is space between each element. Now that we have our JSON array ready, we can move forward to the next and final step, converting it into a String array.
🌐
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
Java programming tutorial to convert JSON array to String array with example, by using Gson library. Though you can also use other open source library, Gson seems easy to me.
Top answer
1 of 6
2

The problem is not the JSONArray.toString(), as @Selvin mentioned.

From JSONArray source:

/**
 * Encodes this array as a compact JSON string, such as:
 * <pre>[94043,90210]</pre>
 */
@Override public String toString() {
    try {
        JSONStringer stringer = new JSONStringer();
        writeTo(stringer);
        return stringer.toString();
    } catch (JSONException e) {
        return null;
    }
}

/**
 * Encodes this array as a human readable JSON string for debugging, such
 * as:
 * <pre>
 * [
 *     94043,
 *     90210
 * ]</pre>
 *
 * @param indentSpaces the number of spaces to indent for each level of
 *     nesting.
 */
public String toString(int indentSpaces) throws JSONException {
    JSONStringer stringer = new JSONStringer(indentSpaces);
    writeTo(stringer);
    return stringer.toString();
}

The problem is that you need to convert your ChecklistAnswer to JSON object first for your JSONArray to work properly.

Again from Javadoc:

/**
 * A dense indexed sequence of values. Values may be any mix of
 * {@link JSONObject JSONObjects}, other {@link JSONArray JSONArrays}, Strings,
 * Booleans, Integers, Longs, Doubles, {@code null} or {@link JSONObject#NULL}.
 * Values may not be {@link Double#isNaN() NaNs}, {@link Double#isInfinite()
 * infinities}, or of any type not listed here.

...

2 of 6
1

In my ChecklistAnwer class i added:

   public JSONObject toJsonObject(){
    JSONObject json = new JSONObject();

    try {
        json.put("questionId", questionId);
        json.put("checklistId", checklistId);
        json.put("answer", answer);
        json.put("remark", remark);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return json;
}

and in my other class:

JSONArray answers = new JSONArray();

ChecklistAnswer answer = new ChecklistAnswer(questions.get(id).id, 2, cb.isChecked(),         text.getText().toString());

answers.put(answer.toJsonObject());

if i filled the array:

String js = answers.toString(1);

and that returns:

[
 {
  "answer": true,
  "questionId": 1,
  "remark": "",
  "checklistId": 2
 },
 {
  "answer": false,
  "questionId": 4,
  "remark": "teesxfgtfghyfj",
  "checklistId": 2
 },
 {
  "answer": true,
  "questionId": 4,
  "remark": "",
  "checklistId": 2
 },
 {
  "answer": true,
  "questionId": 4,
  "remark": "",
  "checklistId": 2
 },
 {
  "answer": true,
  "questionId": 4,
  "remark": "",
  "checklistId": 2
 },
 {
  "answer": true,
  "questionId": 4,
  "remark": "",
  "checklistId": 2
 },
 {
  "answer": true,
  "questionId": 4,
  "remark": "",
  "checklistId": 2
 }
]

thanks to @Selvin

🌐
TutorialsPoint
tutorialspoint.com › article › how-can-we-convert-a-jsonarray-to-string-array-in-java
How can we convert a JSONArray to String Array in Java?
We can convert a JSONArray to String Array by using a simple loop as shown in the example below - import org.json.*; import java.util.*; public class JsonArraytoStringArrayTest { public static void main(String[] args) { JSONArray jsonArray = new JSONArray(); jsonArray.put("INDIA "); jsonArray.put("AUSTRALIA "); jsonArray.put("SOUTH AFRICA "); jsonArray.put("ENGLAND "); jsonArray.put("NEWZEALAND "); List < String > list = new ArrayList < String > (); for (int i = 0; i < jsonArray.length(); i++) { list.add(jsonArray.getString(i)); } System.out.print("JSONArray: " + jsonArray); System.out.print("\n"); String[] stringArray = list.toArray(new String[list.size()]); System.out.print("String Array: "); for (String str: stringArray) { System.out.print(str); } } }
🌐
Wordpress
javarevisited.wordpress.com › 2024 › 09 › 26 › how-to-convert-json-array-to-string-array-in-java-gson-example
How to Convert JSON array to String array in Java – GSon example | Java Prorgram Examples
September 26, 2024 - As I said earlier, there are lots of open-source libraries out there that can help to parse JSON data format and we have already seen Jackson library in our last 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.
Find elsewhere
🌐
Kode Java
kodejava.org › how-do-i-convert-array-into-json
How do I convert array into JSON? - Learn Java by Examples
May 31, 2024 - Buku Java ID · By Wayan in Google Gson Last modified: May 31, 2024 2 Comments · In the example below you can see how to convert an array into JSON string. We serialize the array to JSON using the Gson.toJson() method. To deserialize a string ...
Top answer
1 of 3
47

To have a string value inside your JSON array, you must remember to backslash escape your double-quotes in your Java program. See the declaration of s below.

String s = "[[\"110917       \", 3.0099999999999998, -0.72999999999999998, 2.8500000000000001, 2.96, 685.0, 38603.0], [\"110917    \", 2.71, 0.20999999999999999, 2.8199999999999998, 2.8999999999999999, 2987.0, 33762.0]]";

Your code in the main() method works fine. Below is just a minor modification of your code in the main() method.

System.out.println("String to Json Array Stmt");
JsonParser parser = new JsonParser();
JsonElement tradeElement = parser.parse(s);
JsonArray trade = tradeElement.getAsJsonArray();
System.out.println(trade);

Lastly, remember to prefix your statement "com.google.gson.*" with the keyword "import", as shown below.

import com.google.gson.*;
2 of 3
11

I don't see the problem. This code runs fine for me:

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;


public class GsonExample {
    public static void main(String[] args) {
        String s= "[[\"110917\", 3.0099999999999998, -0.72999999999999998," +
                "2.8500000000000001, 2.96, 685.0, 38603.0], [\"110917\", 2.71," +
                "0.20999999999999999, 2.8199999999999998, 2.8999999999999999," +
                "2987.0, 33762.0]]";


        JsonParser  parser = new JsonParser();
        JsonElement elem   = parser.parse( s );

        JsonArray elemArr = elem.getAsJsonArray();
        System.out.println( elemArr );
    }
}

The only problem maybe is that you failed to properly escape the double quotes in your s string literal.

🌐
Stleary
stleary.github.io › JSON-java › org › json › JSONArray.html
JSONArray
The internal form is an object ... or the JSONObject.NULL object. The constructor can convert a JSON text into a Java object. The toString method converts to JSON text....
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"}

🌐
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.model; public class Person { private String name; private int age; public Person() { } public Person(String name, int age) { this.name = name; this.age = age; } // getters, setters, toString() } In Jackson, we can convert the JSON array to an Array or List. ... package com.mkyong.json.jackson; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.mkyong.json.model.Person; import java.util.List; public class JsonArrayToObjectExample { public static void main(String[] args) throws JsonProcessingException { String jsonArray = "[{\"name\":\"mkyong\", \"age\":42}, {\"name\":\"ah pig\", \"age\":20}]"; ObjectMapper mapper = new ObjectMapper(); // 1.