MyNameIsHans
MyNameIsHans

Reputation: 684

Gson: Change the way Map-Keys are being serialized

Ok so I have a Map<Vector3i,String> that I want to save, problem is, that I only need the x,z values, so the result should look something like this:

{
  "1,2": "test"
  "13,5": "test"
  "9,4": "test"
}

That's my JsonSerializer<Vector3i>:

public class Vector3iAdapter implements JsonSerializer<Vector3i> {
     @Override
     public JsonElement serialize(Vector3i src, Type typeOfSrc, JsonSerializationContext context) {
        return new JsonPrimitive(src.getX()+","+ src.getZ());
     }
}

But that's what the output looks like:

{
  "(1, 0, 2)": "test"
  "(13, 0, 5)": "test"
  "(9, 0, 4)": "test"
}

Since serializing a Vector3i that doesn't function as key in a Map works as intended, I'm asking, why it's behaving differently and how I would fix that.

Upvotes: 1

Views: 658

Answers (1)

david.mihola
david.mihola

Reputation: 12992

I think calling enableComplexMapKeySerialization() on your Gson.Builder should do the trick. From the Gson documentation:

Enabling this feature will only change the serialized form if the map key is a complex type (i.e. non-primitive) in its serialized JSON form. The default implementation of map serialization uses toString() on the key; however, when this is called then one of the following cases apply...

Also, if you are planning to also deserialize the JSON later, you should read this answer: https://stackoverflow.com/a/14677564/763935

Upvotes: 2

Related Questions