Libgdx Json serialization of HashMap

So I got a problem when trying to serialize a HashMap<Integer, Actions> where the Actions are an enum type.
If I try to deserialize the HashMap, the keys are not integers anymore but strings and I have absolutely no idea how to fix this.
I would really appreciate some help :slight_smile:

This is the code:


HashMap<Integer, Actions> val = new HashMap<Integer,Actions>();
		val.put(0, Actions.Left);
		val.put(1, Actions.Right);
		FileHandle file = new FileHandle("test.json");
		file.writeString(json.toJson(val, HashMap.class), false);
		HashMap<Integer,Actions> newVal = json.fromJson(HashMap.class, file);
		System.out.println(newVal.get("0"));

Answer is here : http://stackoverflow.com/questions/12468764/jackson-enum-serializing-and-deserializer.
Look at the answer labeled with “Actual answer”.

What`s the cpnnection between the serializer in zhe post (jackson) and the one libgdx is using? If I deserialize the hashmap the enum is fine but the integers are strings.

They are not connected, one is just better than the other :smiley:

Sorry, In slightly mixed up.
Hope this is more appropriate: http://sblackwell.com/blog/2014/05/loading-intmaps-from-json-with-libgdx/

So I should change the HashMap to an IntMap? I don’t really see why an IntMap (never have seen this before) should be better than a simple HashMap, can somebody explain that? I am just confused because I thought that the Json serializer should be able to serialize a simple HashMap a standard java datastructure but it doesn’t seem to be able to do that and it’s quite strange that I should adapt my datastructures because of that…

So what would you do to solve this problem?

It’s about HashMap and IntMap:

[quote]Second issue, for HashMap it treats keys as Strings, sorry. You could write a serialzier for HashMap that tried to write out the type of the keys. You’d be better off using IntMap though, which again will need a specialized serialzier.
[/quote]

Javadoc for intMap:https://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/utils/IntMap.html

  1. please look at the previuos post.
  2. IntMap is a bit faster than HashMap (at least get operation).
  3. You still might use HashMap and convert it to IntMap (and back) when serializing/deserializing.

I’ve used jackson in the past and it works really well, there are many json libraries out there some are good and some are bad.

Read about some of them

http://www.developer.com/lang/jscript/top-7-open-source-json-binding-providers-available-today.html

The lbgdx one isn’t that well known so I can’t comment much, I just know its not a dedicated library just for json. If other libraries solve your issue then there is no reason why you couldn’t use them.