Last active
April 22, 2016 13:59
-
-
Save MinceMan/14a3d922a5816785359b to your computer and use it in GitHub Desktop.
How to serialize and de-serialize an unknown class with GSON.
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
package com.example; | |
@JsonAdapter(JsonWrapperAdapter.class) | |
public class JsonWrapper { | |
private static final String classNameKey = "className"; | |
private static final String wrappedObjectKey = "wrappedObject"; | |
private final String className; | |
private final Object wrappedObject; | |
private JsonWrapper(Object object) { | |
wrappedObject = object; | |
className = object.getClass().getName(); | |
} | |
} |
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
package com.example; | |
public class JsonWrapperAdapter extends TypeAdapter<JsonWrapper> { | |
private static final String TAG = JsonWrapperAdapter.class.getSimpleName(); | |
@Override | |
public void write(JsonWriter out, JsonWrapper wrapper) throws IOException { | |
out.beginObject(); | |
out.name(JsonWrapper.classNameKey); | |
out.value(wrapper.className); | |
out.name(JsonWrapper.wrappedObjectKey); | |
out.value(IntentHelper.getGson().toJson(wrapper.wrappedObject, wrapper.wrappedObject.getClass())); | |
out.endObject(); | |
} | |
@Override | |
public JsonWrapper read(JsonReader in) throws IOException { | |
String className = null; | |
String classObjectString = null; | |
in.beginObject(); | |
while (in.hasNext()) { | |
String next = in.nextName(); | |
if (JsonWrapper.classNameKey.equals(next)) { | |
className = in.nextString(); | |
} else if (JsonWrapper.wrappedObjectKey.equals(next)) { | |
classObjectString = in.nextString(); | |
} | |
} | |
in.endObject(); | |
if (TextUtils.isEmpty(className) || TextUtils.isEmpty(classObjectString)) return null; | |
try { | |
Class<?> clazz = Class.forName(className); | |
Object object = IntentHelper.getGson().fromJson(classObjectString, clazz); | |
return new JsonWrapper(object); | |
} catch (ClassNotFoundException | ClassCastException | JsonParseException e) { | |
Log.e(TAG, "Exception when trying to deserialize your JsonWrapper.", e); | |
return null; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The only bad part about this is you have to know the class to deserialize this. This won't work with server stuff.