Skip to content

Instantly share code, notes, and snippets.

@cuchas
Created March 22, 2016 16:36
Show Gist options
  • Save cuchas/bbff3166599e0ef62bf1 to your computer and use it in GitHub Desktop.
Save cuchas/bbff3166599e0ef62bf1 to your computer and use it in GitHub Desktop.
Gson HashMap Deserializer
public class HashMapStringStringArrayDeserializer implements JsonDeserializer<HashMap<String, String[]>> {
@Override
public HashMap<String, String[]> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
Iterator<Map.Entry<String, JsonElement>> iterator = json.getAsJsonObject().entrySet().iterator();
HashMap<String, String[]> map = new HashMap<>();
while(iterator.hasNext()) {
Map.Entry<String, JsonElement> next = iterator.next();
JsonArray asJsonArray = next.getValue().getAsJsonArray();
List<String> l = new ArrayList<>(asJsonArray.size());
for (JsonElement j : asJsonArray) {
l.add(j.getAsString());
}
String[] x = new String[asJsonArray.size()];
x = l.toArray(x);
map.put(next.getKey(), x);
}
return map;
}
}
public class HashMapStringStringDeserializer implements JsonDeserializer<HashMap<String, String>> {
@Override
public HashMap<String, String> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
Iterator<Map.Entry<String, JsonElement>> iterator = json.getAsJsonObject().entrySet().iterator();
HashMap<String, String> map = new HashMap<>();
while(iterator.hasNext()) {
Map.Entry<String, JsonElement> next = iterator.next();
String s = next.getValue().toString();
map.put(next.getKey(), s);
}
return map;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment