Reputation: 279
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!
Upvotes: 14
Views: 8800
Reputation: 45
ArrayList<Tile> board = json.fromJson(ArrayList.class, Tile.class,
Gdx.files.internal("data/tiles.json").readString());
2 years and the libgdx has changed a little, so to managed to make it work. Now we have to add .readString()
. I was stuck until I figured this out.
Upvotes: 1
Reputation: 232
The answer from Tanmay Patil is right but you can save the loop with:
ArrayList<Tile> board = json.fromJson(ArrayList.class, Tile.class, Gdx.files.internal("data/tiles.json"));
Upvotes: 9
Reputation: 7057
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.
Upvotes: 9