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!
These files are read-only. libGDX only uses the assets mechanism, as it provides raw access to the byte streams and more closely resembles a traditional filesystem. Resources better lend themselves to normal Android applications but introduce problems when used in games.
; Using Jackson's ObjectMapper class, it's easy to read values and map them to an object, or an array of objects. We just use the readValue () method, passing the JSON contents and the class we'd like to map to. Since we're mapping to an array of Language, we'll also specify this in the readValue () method:
Learn to read all the lines from a file into ArrayList using Java IO APIs, Common IO and Guava classes. Remember that reading the whole file into memory is recommended only for small text files where we may want to refer to the file content multiple times in the program. In such cases, reading the file multiple times is not an ideal solution.
In this article, we'll convert a JSON array into a Java Array and Java List using Jackson. Since we're using Jackson, you'll have to add it to your project. If you're using Maven, it's as easy as adding the dependency: Since we're mapping from JSON to our own objects, let's go ahead and define a POJO:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With