generic serialization with logansquared
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
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 { | |
} | |
} |
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
@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