Skip to content

Instantly share code, notes, and snippets.

@t81lal
Created February 1, 2015 23:29
Show Gist options
  • Save t81lal/0703a7c2e709811ff3fa to your computer and use it in GitHub Desktop.
Save t81lal/0703a7c2e709811ff3fa to your computer and use it in GitHub Desktop.
package org.topdank.cfide.io.gson;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.google.gson.reflect.TypeToken;
@SuppressWarnings({ "rawtypes", "unchecked" })
public class HashMapSerializer implements JsonSerializer<HashMap>, JsonDeserializer<HashMap> {
@Override
public HashMap deserialize(JsonElement e, Type type, JsonDeserializationContext context) throws JsonParseException {
try {
JsonObject obj = e.getAsJsonObject();
Set<Entry<String, JsonElement>> elementSet = obj.entrySet();
Map<String, Object> result = new HashMap<String, Object>(elementSet.size());
for (Entry<String, JsonElement> outerEntry : obj.entrySet()) {
Class<?> clazz = null;
JsonElement valElement = null;
for (Entry<String, JsonElement> innerEntry : outerEntry.getValue().getAsJsonObject().entrySet()) {
if (innerEntry.getKey().equals("class")) {
clazz = Class.forName(innerEntry.getValue().getAsString());
} else if (innerEntry.getKey().equals("val")) {
valElement = innerEntry.getValue();
}
}
Type clazzType = TypeToken.get(clazz).getType();
Object o = context.deserialize(valElement, clazzType);
result.put(outerEntry.getKey(), o);
}
return (HashMap) result;
} catch (Throwable t) {
return context.deserialize(e, type);
}
}
@Override
public JsonElement serialize(HashMap map, Type type, JsonSerializationContext context) {
JsonObject result = new JsonObject();
for (Entry<String, Object> entry : (Set<Entry<String, Object>>) map.entrySet()) {
JsonObject resultEntryObject = new JsonObject();
Object toSerialiseValue = entry.getValue();
resultEntryObject.add("class", new JsonPrimitive(toSerialiseValue.getClass().getCanonicalName()));
resultEntryObject.add("val", context.serialize(toSerialiseValue));
result.add(entry.getKey(), resultEntryObject);
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment