#6 LibGDX Jam


JSON serialization here I come! Now the GameWorld can be saved as a json file and also loaded from a file.

LibGDX json

LibGDX is able to read and write object graphs to and from json. This is done via reflection, but there are some cases, where the default serialization is not good enough. In my case there a world consists of different rooms and each room has different connections. When two rooms are connected to one another, each room will have a connection, with a reference to the other room. This circular dependency is a bit problematic, so I decided to do the serialization for some classes by myself.
So if a connection object is connected to another room, I just store the ID of that room inside the json object. When the connection is deserialized, I read the ID and store it until all rooms are loaded. Then I post iterate over all connections and fetch the target room from the GameWorld by its ID.
I also had a problem with (de)serializing an ObjectIntMap. After serializing and deserializing an ObjectIntMap, it's content was not the same! Maybe because the key was an enumeration, but that's just a guess. It also creates a lot of zeros, and in my implementation I skipped them:

for(ObjectIntMap.Entry<Resource> entry : this.resources)
  if(entry.value > 0) json.writeValue(entry.key.ordinal());
for(ObjectIntMap.Entry<Resource> entry : this.resources)
  if(entry.value > 0) json.writeValue(entry.value);

This will result in something like this:

{ // some other stuff
  keys: [4]
  values: [51]

Not exactly json...

json is a nice format (and a million times better than XML), but there are also some not so nice things. For example in a normal json file the key of a map has to be a string, also the right handside has to be null, true, false, a number, a string, an array or an object. But obviously it would be much better to allow also simple identifiers on both sides. As you can see, standard json is a bit odd.
And now we bring LibGDX in:
It is able to produce not only standard json, but also the "improved" version of json! So the following code will be valid json in LibGDX:

  localPosition: { x: 32, y: 48 }
  direction: SOUTH

As you can see, we can also skip some commas!
The standard json would look like this:

  "localPosition": { "x": 32, "y": 48 },
  "direction": "SOUTH"