I implemented my own serializer, which takes an object and looks at it. If a field is annotated using @MyCustomAnnotation, I change the value of this field to hide some sensitive data. Other fields in the object must be standardized in order. The problem is that my serializer does not serialize nested objects to json string view
public class CustomSerializer extends JsonSerializer<Object> { @Override public void serialize(Object value, JsonGenerator jGen, SerializerProvider serializers) throws IOException { jGen.writeStartObject(); Field[] fields = value.getClass().getDeclaredFields(); for (Field field: fields) { field.setAccessible(true); try { Object fieldValue = field.get(value); String fieldName = field.getName(); if (fieldValue != null) { if (field.isAnnotationPresent(MyCustomAnnotation.class)) { jGen.writeStringField(fieldName, changeMyField(fieldValue.toString())); } else { jGen.writeStringField(fieldName, fieldValue.toString()); } } } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } jGen.writeEndObject(); }
If the field in the object is not annotated by my custom annotation, it is serialized as a toString () view, so if I serialize the object, for example:
public class TestObject { @MyCustomAnnotation private String fieldOne; private OtherType fieldTwo; }
then the output is not json, because it uses the toString () method for fieldTwo, but does not serialize it to json.
How can I achieve this behavior in order to deeply serialize an object with all nested objects (for example, here OtherType) in a custom serializer?
If I replace the line:
} else { jGen.writeStringField(fieldName, fieldValue.toString()); }
for:
jGen.writeObjectField(fieldName, fieldValue);
then I get this exception:
com.fasterxml.jackson.core.JsonGenerationException: Can not start an object, expecting field name (context: Object)