libGDX comes with a JSON serializer/deserializer that let’s you move data between JSON files and your Java data structures with just a few lines of code. This works mostly automatically, even with more complex data hierarchies.
We’ll start with an example of how this works, then how it breaks when reading an IntMap, and finally how to fix it.
For the working example, let’s take this class:
1 2 3 4 |
public class MyData { float[] values; Array<String> names; } |
And this JSON:
1 2 3 4 5 6 7 8 9 10 |
{ "first": { "values": [ 0.11235, 0.81321 ], "names": [ "John", "Jacob" ] }, "second": { "values": [ 3.14159 ], "names": [ "Jingleheimer", "Schmidt" ] } } |
Then you can deserialize the JSON to an ObjectMap with
1 2 3 |
FileHandle file = Gdx.files.internal("data.json"); Json json = new Json(); ObjectMap<String, MyData> dataMap = json.fromJSON(ObjectMap.class, file); |
Boom! Done. You can focus on data structures and data, and not worry about how to move them back and forth. Unless you try to pull the same trick with an IntMap…
Continue reading →