Created
December 29, 2012 08:50
-
-
Save Mithrandir0x/4405524 to your computer and use it in GitHub Desktop.
A class created by Brian Nettleton that allows to transform a JSON string to a Map object for GSON. To use it, just register a new Type Adapter for Object.class.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @author Brian Nettleton | |
*/ | |
class GenericObjectDeserializer implements JsonDeserializer<Object> | |
{ | |
@Override | |
public Object deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException | |
{ | |
if( json.isJsonNull() ) { | |
return null; | |
} | |
else if ( json.isJsonPrimitive() ) { | |
JsonPrimitive primitive = json.getAsJsonPrimitive(); | |
if ( primitive.isString() ) { | |
return primitive.getAsString(); | |
} | |
else if ( primitive.isNumber() ) { | |
return primitive.getAsNumber(); | |
} | |
else if ( primitive.isBoolean() ) { | |
return primitive.getAsBoolean(); | |
} | |
} | |
else if ( json.isJsonArray() ) { | |
JsonArray array = json.getAsJsonArray(); | |
List<Object> result = new ArrayList<Object>(array.size()); | |
/* Object[] result = new Object[array.size()]; */ | |
int i = 0; | |
for( JsonElement element : array ) { | |
/* result[i] = deserialize(element, null, context); */ | |
result.set(i, deserialize(element, null, context)); | |
++i; | |
} | |
return result; | |
} | |
else if ( json.isJsonObject() ) { | |
JsonObject object = json.getAsJsonObject(); | |
Map<String, Object> result = new HashMap<String,Object>(); | |
for( Map.Entry<String, JsonElement> entry : object.entrySet() ) { | |
Object value = deserialize(entry.getValue(), null, context); | |
result.put(entry.getKey(), value); | |
} | |
return result; | |
} | |
else { | |
throw new JsonParseException("Unknown JSON type for JsonElement " + json.toString()); | |
} | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment