Search code examples
javajsontiled

Load data from JSON file generated by Tiled using org.json.simple


Newbie here... I need to address the following two "data" arrays in this JSON file individually so I can save them in different int arrays:

{ 
//other stuff ...
"layers":[
{"data":[1, 1, 1, 1, 5, 1, 1, 1...],
//other stuff ...
}, 
{"data":[1, 1, 1, 1, 5, 1, 1, 1...],
//other stuff...
}
],
//other stuff...
}

thats the code I have so far :

@SuppressWarnings("unchecked")
    private void loadJsonData() {
        JSONParser parser = new JSONParser();
        try {
            Object obj = parser.parse(new FileReader(path));
            String jsonStr = obj.toString();
            JSONObject json = (JSONObject) JSONValue.parse(jsonStr);

          //other code...

          mapTiles = ...;
          objectTiles = ...;

        } catch (ParseException ex) {
            ex.printStackTrace();
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (ClassCastException ex) {
            ex.printStackTrace();
        }
    }

Im sure the answer is somwehere out there but Im too incompetent to find it :D


Solution

  • There are a ton of resources and the json org library is easy to use.

    You can find more EXAMPLES over here

        JSONParser parser = new JSONParser();
        Object parsedObject = parser.parse(jsonStr);
    
        JSONObject jsonObject = (JSONObject) parsedObject;
        JSONArray layers = (JSONArray) jsonObject.get("layers"); 
    
        JSONObject data = (JSONObject) layers.get(0);   
        JSONArray mapData = (JSONArray) data.get("data");   
        int[] mapTile = new int[mapData.size()];
        for (int i = 0; i < mapData.size(); i++) {
            mapTile[i] = ((Long)mapData.get(i)).intValue();
        }
    
        data = (JSONObject) layers.get(1);  
        JSONArray objectData = (JSONArray) data.get("data");    
        int[] objectTile = new int[objectData.size()];
        for (int i = 0; i < objectData.size(); i++) {
            objectTile[i] = ((Long)objectData.get(i)).intValue();
        }
    
        System.out.println(Arrays.toString(mapTile));
        System.out.println(Arrays.toString(objectTile));