Skip to content

Instantly share code, notes, and snippets.

@MinceMan
Last active April 22, 2016 13:59
Show Gist options
  • Save MinceMan/14a3d922a5816785359b to your computer and use it in GitHub Desktop.
Save MinceMan/14a3d922a5816785359b to your computer and use it in GitHub Desktop.
How to serialize and de-serialize an unknown class with GSON.
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();
}
}
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;
}
}
}
@MinceMan
Copy link
Author

MinceMan commented Feb 21, 2015

The only bad part about this is you have to know the class to deserialize this. This won't work with server stuff.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment