Jackson replace field with a Custom Serializer

This code snipped shows you how can you can replace field with a custom serializer. This might be helpful if you want to modify or ignore certain fields.

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();
   }

}

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

This site uses Akismet to reduce spam. Learn how your comment data is processed.