LibGDX: Reading from json file to ArrayList
java, json, libgdx
Solution
Your json file has `ArrayList<Tile>` stored in it and you are trying to read it as a `Tile`.
There are two ways to rectify this.
1) You can encapsulate collection of tiles in another class to simplify serialization.
2) Read as `ArrayList` and convert type later.
ArrayList<JsonValue> list = json.fromJson(ArrayList.class,
Gdx.files.internal("data/tiles.json"));
for (JsonValue v : list) {
tilesData.add(json.readValue(Tile.class, v));
}
Hope this helps.
Problem
I need help with reading json file to ArrayList. I have json file: ``` [ { "name": "Wall", "symbol": "#", }, { "name": "Floor", "symbol": ".", } ] ``` I have a class: ``` public class Tile { public String name; public String symbol; } ``` And I have another class with ArrayList: ``` public class Data { public static ArrayList<Tile> tilesData; public static void loadData() { tilesData = new ArrayList<Tile>(); Json json = new Json(); json.fromJson(Tile.class, Gdx.files.internal("data/tiles.json")); } } ``` I need to fill this ArrayList with data from json file, but I have some problems. I guess the line ``` json.fromJson(Tile.class, Gdx.files.internal("data/tiles.json")); ``` is wrong. When I try to run it there is ``` Exception in thread "LWJGL Application" com.badlogic.gdx.utils.SerializationException: Error reading file: data/tiles.json Caused by: com.badlogic.gdx.utils.SerializationException: Unable to convert value to required type: [ { name: Wall, symbol: # }, { name: Floor, symbol: . } ``` I have read the libgdx article about json files, but I found it unclear... I don't understand how to fill array. Please, help me with this case!