Jackson replace field with a Custom Serializer

  • Posted on: 12 September 2017
  • By: robin
private class CustomValueSerializer extends StdSerializer<WebTemplateResource> {
   private final String url;

   public CustomValueSerializer(String url) {
      super(WebTemplateResource.class);
      this.url = url;
   }

   @Override
   public void serialize(WebTemplateResource res, JsonGenerator jgen, SerializerProvider serializerProvider) throws IOException {

      jgen.writeStartObject();
      Field[] fields = res.getClass().getDeclaredFields();
      jgen.writeObjectField("htmlUrl", url);

      for (Field field : fields) {
         try {
            field.setAccessible(true);

            String name = field.getName();
            if (name.equals("htmlContent")) continue;
            jgen.writeObjectField(name, field.get(res));

         } catch (IllegalArgumentException | IllegalAccessException e) {
            e.printStackTrace();
         }
      }
      jgen.writeEndObject();
      jgen.close();
   }

}