{@code MapThe above code prints this JSON object:original = new LinkedHashMap (); original.put(new Point(5, 6), "a"); original.put(new Point(8, 8), "b"); System.out.println(gson.toJson(original, type));}
{@code}{ "(5,6)": "a", "(8,8)": "b" } }But GSON is unable to deserialize this value because the JSON string name is just the {@link Object#toString() toString()} of the map key. Attempting toconvert the above JSON to an object fails with a parse exception:
com.massivecraft.mcore2.lib.gson.JsonParseException: Expecting object found: "(5,6)" at com.massivecraft.mcore2.lib.gson.JsonObjectDeserializationVisitor.visitFieldUsingCustomHandler at com.massivecraft.mcore2.lib.gson.ObjectNavigator.navigateClassFields ...
Register this adapter when you are creating your GSON instance.
{@code Gson gson = new GsonBuilder() .registerTypeAdapter(Map.class, new MapAsArrayTypeAdapter()) .create();}This will change the structure of the JSON emitted by the code above. Now we get an array. In this case the arrays elements are map entries:
{@code [ [}{ "x": 5, "y": 6 }, "a", ], [ { "x": 8, "y": 8 }, "b" ] ] }This format will serialize and deserialize just fine as long as this adapter is registered.
|
|