Java – libgdx: read from JSON file to ArrayList
•
Java
I need help reading the JSON file to ArrayList
I have JSON files:
[ { "name": "Wall","symbol": "#",},{ "name": "Floor","symbol": ".",} ]
I have a class:
public class Tile { public String name; public String symbol; }
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 populate the ArrayList with the data in the JSON file, but I have some problems I guess the line
json.fromJson(Tile.class,Gdx.files.internal("data/tiles.json"));
It's wrong
When I try to run it
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've read the libgdx article on JSON files, but I find it unclear... I don't understand how to fill arrays Please help me with this case!
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 correct the problem
1) You can encapsulate the collection of tiles in another class to simplify serialization
2) Read the ArrayList and convert the 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)); }
I hope this will help
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码