MrEngineer13 MrEngineer13 - 4 months ago 13
JSON Question

How to structure a Map from Json that has duplicate keys

Ok so I have this piece of JSON that I want to parse with Gson. I would like the Strings to be the values and the longs to be the keys.


{"completed_questions":[["String",12345],...]}


The issue is the data type, when I try a
Map<String, Long>
it parses everything but gives me an error because of the duplicate String keys.

I tried to reverse it thinking Gson would know to switch them around but when I tried
Map<Long, String>
I got an error about not being able to parse my Strings as Longs.

To get it to work I created a swap map class that takes the Key and Value types and swaps them like so
public class SwapMap<K, V> implements Map<K, V>
however translating the swapped map actions like put/get/remove seem to be pretty difficult to make work.

What's the best way to parse this with Gson even though the strings aren't unique? (But the numbers are)

Answer

So what I did is just made a custom Gson Deserializer that mapped these values to a LongSparseArray<String>, which is the best way to go about it.

This is the relevant parts of the Deserializer:

for (JsonElement array : jsonObject.get("my_key").getAsJsonArray()) {
    if (array.getAsJsonArray().size() == 2) {
      String value = array.getAsJsonArray().get(VALUE).getAsString();
      long key = array.getAsJsonArray().get(KEY).getAsLong();
      progress.completedActivities.put(key, value);
    }
  } 

Then I just added it to my Gson creator like so:

@Provides @Singleton Gson provideGson() {
return new GsonBuilder()
    .registerTypeAdapter(MyClass.class, new MyClass())
    .create();
}