jsam
jsam

Reputation: 53

Gson serialization of Hashmaps

I have a hashmap of hashmaps which needs to be serialized ( Map < String, Hashmap >) , deals only with Strings at the moment. Currently use gson to serialize it.

{cb9b4b3d-8d2e-41b2-9a21-1657dbd14f58={tz:"eeee" dis:"aaaa" geoAddr:"cccc,dddd" id:@cb9b4b3d-8d2e-41b2-9a21-1657dbd14f58 geoState:"dddd" area:1000ft² geoCity:"cccc" bbbb}}

Gson gson = new GsonBuilder().create();
String string = gson.toJson(map);

But seem to change the overall structure by adding intermediate key-value pairs and a hash code as below.

{"cb9b4b3d-8d2e-41b2-9a21-1657dbd14f58":{"map":{"tz":{"val":"eeee"},"dis":{"val":"aaaa"},"geoAddr":{"val":"cccc,dddd"},"id":{"val":"cb9b4b3d-8d2e-41b2-9a21-1657dbd14f58"},"geoState":{"val":"dddd"},"area":{"val":1000.0,"unit":"ft²"},"geoCity":{"val":"cccc"},"bbbb":{}},"hashCode":0}}

When I deserialize this back to Map , I end up having the extra key value pairs.

Gson gson = new Gson();
Type listType = new TypeToken<Map<String, Map>>()
{
}.getType();
map = gson.fromJson(string, listType); 

{cb9b4b3d-8d2e-41b2-9a21-1657dbd14f58={map={tz={val=eeee}, dis={val=aaaa}, geoAddr={val=cccc,dddd}, id={val=cb9b4b3d-8d2e-41b2-9a21-1657dbd14f58}, geoState={val=dddd}, area={val=1000.0, unit=ft²}, geoCity={val=cccc}, bbbb={}}, hashCode=0.0}}

Is there a way I can deserialize the to the same struct as it was originally. I use a third party library which does not to understand this deserialized Map.

Upvotes: 0

Views: 88

Answers (1)

teppic
teppic

Reputation: 7286

This works for me (gson 2.8):

public static void main(String[] args) {
    String json = "{"
        + "  \"cb9b4b3d-8d2e-41b2-9a21-1657dbd14f58\": {"
        + "    \"tz\": \"eeee\","
        + "    \"dis\": \"aaaa\","
        + "    \"geoAddr\": \"cccc\","
        + "    \"id\": \"cb9b4b3d-8d2e-41b2-9a21-1657dbd14f58\","
        + "    \"geoState\": \"dddd\","
        + "    \"area\": 1000,"
        + "    \"geoCity\": \"cccc\""
        + "  }"
        + "}";

    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    Map<String, Map<String, Object>> map = gson.fromJson(json, new TypeToken<Map<String, Map<String, Object>>>(){}.getType());
    System.out.println("Map.toString() is:");
    System.out.println(map);
    String serialisedMap = gson.toJson(map);
    System.out.println("Map to json is:");
    System.out.println(serialisedMap);
}

Prints:

Map.toString() is:
{cb9b4b3d-8d2e-41b2-9a21-1657dbd14f58={tz=eeee, dis=aaaa, geoAddr=cccc, id=cb9b4b3d-8d2e-41b2-9a21-1657dbd14f58, geoState=dddd, area=1000.0, geoCity=cccc}}
Map to json is:
{
  "cb9b4b3d-8d2e-41b2-9a21-1657dbd14f58": {
    "tz": "eeee",
    "dis": "aaaa",
    "geoAddr": "cccc",
    "id": "cb9b4b3d-8d2e-41b2-9a21-1657dbd14f58",
    "geoState": "dddd",
    "area": 1000.0,
    "geoCity": "cccc"
  }
}

Upvotes: 1

Related Questions