Beispiel #1
0
 public DateObjectMapper() {
   CustomSerializerFactory factory = new CustomSerializerFactory();
   factory.addGenericMapping(
       Date.class,
       new JsonSerializer<Date>() {
         @Override
         public void serialize(
             Date value, JsonGenerator jsonGenerator, SerializerProvider provider)
             throws IOException, JsonProcessingException {
           SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
           jsonGenerator.writeString(sdf.format(value));
         }
       });
   setSerializerFactory(factory);
 }
 @Override
 public void afterPropertiesSet() throws Exception {
   jsonProvider.setMapper(jacksonMapper);
   jacksonMapper.setSerializerFactory(serializerFactory);
   jacksonMapper.setSerializationInclusion(Inclusion.NON_NULL);
   serializerFactory.addSpecificMapping(BigInteger.class, this);
 }
    /**
     * Here we will modify serializer such that it has two modes: default handling when no JsonView
     * is enabled; and other (custom) when viess are enabled. Note that we could also just have
     * forced serialization for all cases.
     */
    @Override
    protected void processViews(SerializationConfig config, BeanSerializerBuilder builder) {
      // Let's use default serializer modification as the baseline
      super.processViews(config, builder);

      /* And only change handling of that one bean (more likely,
       * you would want to handle all classes in a package, or with
       * some name -- this would be less work than having separate
       * custom serializer for all classes)
       */
      BasicBeanDescription beanDesc = builder.getBeanDescription();
      if (beanDesc.getBeanClass() == Bean.class) {
        List<BeanPropertyWriter> props = builder.getProperties();
        BeanPropertyWriter[] writers = props.toArray(new BeanPropertyWriter[props.size()]);
        for (int i = 0; i < writers.length; ++i) {
          String pname = writers[i].getName();
          if ("secret".equals(pname)) {
            // remove serializer, filters it out
            writers[i] = null;
          } else if ("name".equals(pname)) {
            // This one we'll just upper case for fun
            writers[i] = new UpperCasingWriter(writers[i]);
          }
        }
        // Important: update builder with filtered property definitions
        builder.setFilteredProperties(writers);
      }
    }