Skip to content

Instantly share code, notes, and snippets.

@andaag
Last active August 29, 2015 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andaag/ec1339635b5188a6b137 to your computer and use it in GitHub Desktop.
Save andaag/ec1339635b5188a6b137 to your computer and use it in GitHub Desktop.
generic serialization with logansquared
public class GenericTypeConverter implements TypeConverter<GenericTypeConverter.GenericType> {
@Override
public GenericType parse(JsonParser jsonParser) throws IOException {
String field = null;
String value = null;
String fieldType = null;
String data = null;
while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
if (jsonParser.getCurrentToken() == JsonToken.VALUE_STRING) {
value = jsonParser.getValueAsString();
} else if (jsonParser.getCurrentToken() == JsonToken.FIELD_NAME) {
field = jsonParser.getCurrentName();
}
if (value != null && field != null) {
if ("__TYPE".equals(field)) {
fieldType = value;
} else {
data = value;
}
value = null;
field = null;
}
}
try {
Class screenType = (Class) Class.forName(fieldType);
Object o = LoganSquare.parse(data, screenType);
return (GenericType) o;
} catch (ClassNotFoundException e) {
e.printStackTrace();
throw new IllegalStateException(e);
}
}
@Override
public void serialize(GenericType object, String fieldName, boolean writeFieldNameForObject, JsonGenerator jsonGenerator) throws IOException {
jsonGenerator.writeObjectFieldStart(fieldName);
jsonGenerator.writeStringField("__TYPE", object.getClass().getName());
jsonGenerator.writeStringField(fieldName, LoganSquare.serialize(object));
jsonGenerator.writeEndObject();
}
public interface GenericType {
}
}
@JsonObject
public class TestA {
@JsonField GenericType x;
}
@JsonObject
public GenericImpl implements GenericType {
@JsonField String test;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment