I\'m trying to write a custom deserializer for Jackson and I want to make it generic (generic in the sense of working on any type, not as in \"generics\").
However I
Roughly speaking, and without exception catching and error checking...
JsonToken tok = jp.nextValue();
Field field = findField(jp.getCurrentName());
Class> fc = field.getType();
if(fc == int.class) {
field.setInt(this, jp.getIntValue());
} // handle all the primitive types and String in the same way, then...
} ... else if(tok == JsonToken.START_ARRAY) {
if(fc.isArray()) {
// Load into an array
} else if(Collection.class.isAssignableFrom(fc)) {
// Load into a collection
} else {
// throw
}
} else if(tok == JsonToken.START_OBJECT) {
// Recursively create that object from the JSON stream
}
... and loop until tok
is END_OBJECT. To find a of the current class by name:
Field findField(String name) {
for(Class> c = getClass(); c != null; c = c.getSuperclass()) {
for(Field field : c.getDeclaredFields()) {
if(field.getName().equals(name)) {
return field;
}
}
}
}