0

I am developing a small side scroller game using slick 2D lwjgl and am running into a current error while casting something.

It seems to be not recognizing that i'm casting the json string as a JsonArray.

The error and the function,

java.lang.ClassCastException: java.lang.String cannot be cast to org.json.simple.JSONArray
    at world.World.load(World.java:35)
    at game.Engine.initStatesList(Engine.java:64)
    at org.newdawn.slick.state.StateBasedGame.init(StateBasedGame.java:164)

function:

public static void load(String path) throws Exception
{
    JSONParser parser = new JSONParser();
    Object obj = parser.parse(new FileReader(path));
    JSONObject jSonOBJ = (JSONObject)obj;

    JSONArray layers = (JSONArray)jSonOBJ.get("layers");
    int amount = layers.size();

    for (int i = 0; i < amount; ++i)
    {
        JSONObject layer = (JSONObject) layers.get(i);
        String type = (String)layer.get("name");

        if (type.equals("solids"))
        {
            solids = parse((JSONArray)layer.get("data")); //error
        }
        else if (type.equals("spawns"))
        {
            //to-do
        }
    }
}

this is just to parse if the json, my map, tile is a solid or not, but I have been stuck on this small error for a little time. the line of code solids = parse((JSONArray)layer.get("data")); should convert it to JSONArray correct?

RPresle
  • 2,436
  • 3
  • 24
  • 28
SenjuXo
  • 157
  • 10

1 Answers1

0

There is a lot of way to get Object to prevent you from casting everytime. The method getJSONArray will allow you to have directly a JSONArray.

Here is an example taken from this post:

JSONObject jsnobject = new JSONObject(yourString);
JSONArray jsonArray = jsnobject.getJSONArray("nameOfArrayAttribute");
    for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject explrObject = jsonArray.getJSONObject(i);
}

Here you see that you just have to buil your Json Object from your String. Then you can extract your document with specific method to get strong typed object.

Community
  • 1
  • 1
RPresle
  • 2,436
  • 3
  • 24
  • 28
  • Still having trouble with this, `Image[][] solids` is my 2D array of Images. I am simply calling, `solids = ` then parsing, `parse((JSONArray)layer` layer is a JSONObject containing one of the indices of solids, `.get("data")` .get to receive the 2d array via the key "data" thats found inside the layers object on my JSON request – SenjuXo Dec 04 '15 at 16:47
  • Can you provide your JSON text please? And have you tried skipping the cast and calling `solids = layer.getJSONArray("data");` – RPresle Dec 07 '15 at 08:12