Java Code Examples for com.fasterxml.jackson.databind.module.SimpleModule#setSerializerModifier()

The following examples show how to use com.fasterxml.jackson.databind.module.SimpleModule#setSerializerModifier() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AdditionalPropertiesSerializer.java    From botbuilder-java with MIT License 6 votes vote down vote up
/**
 * Gets a module wrapping this serializer as an adapter for the Jackson
 * ObjectMapper.
 *
 * @param mapper the object mapper for default serializations
 * @return a simple module to be plugged onto Jackson ObjectMapper.
 */
public static SimpleModule getModule(final ObjectMapper mapper) {
    SimpleModule module = new SimpleModule();
    module.setSerializerModifier(new BeanSerializerModifier() {
        @Override
        public JsonSerializer<?> modifySerializer(SerializationConfig config, BeanDescription beanDesc, JsonSerializer<?> serializer) {
            for (Class<?> c : TypeToken.of(beanDesc.getBeanClass()).getTypes().classes().rawTypes()) {
                if (c.isAssignableFrom(Object.class)) {
                    continue;
                }
                Field[] fields = c.getDeclaredFields();
                for (Field field : fields) {
                    if ("additionalProperties".equalsIgnoreCase(field.getName())) {
                        JsonProperty property = field.getAnnotation(JsonProperty.class);
                        if (property != null && property.value().isEmpty()) {
                            return new AdditionalPropertiesSerializer(beanDesc.getBeanClass(), serializer, mapper);
                        }
                    }
                }
            }
            return serializer;
        }
    });
    return module;
}
 
Example 2
Source File: FilterableJsonSerializer.java    From caravan with Apache License 2.0 6 votes vote down vote up
public FilterableJsonSerializer(FilterableJsonSerializerConfig config) {
    NullArgumentChecker.DEFAULT.check(config, "config");

    ObjectMapper mapper = new ObjectMapper();

    SimpleModule module = new SimpleModule();
    module.setSerializerModifier(new FilterableBeanSerializerModifier(config));
    mapper.registerModule(module);

    mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
    mapper.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false);
    mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
    mapper.configure(Feature.AUTO_CLOSE_TARGET, false);
    mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);

    _mapper = mapper;
}
 
Example 3
Source File: AdditionalPropertiesSerializer.java    From autorest-clientruntime-for-java with MIT License 6 votes vote down vote up
/**
 * Gets a module wrapping this serializer as an adapter for the Jackson
 * ObjectMapper.
 *
 * @param mapper the object mapper for default serializations
 * @return a simple module to be plugged onto Jackson ObjectMapper.
 */
public static SimpleModule getModule(final ObjectMapper mapper) {
    SimpleModule module = new SimpleModule();
    module.setSerializerModifier(new BeanSerializerModifier() {
        @Override
        public JsonSerializer<?> modifySerializer(SerializationConfig config, BeanDescription beanDesc, JsonSerializer<?> serializer) {
            for (Class<?> c : TypeToken.of(beanDesc.getBeanClass()).getTypes().classes().rawTypes()) {
                if (c.isAssignableFrom(Object.class)) {
                    continue;
                }
                Field[] fields = c.getDeclaredFields();
                for (Field field : fields) {
                    if ("additionalProperties".equalsIgnoreCase(field.getName())) {
                        JsonProperty property = field.getAnnotation(JsonProperty.class);
                        if (property != null && property.value().isEmpty()) {
                            return new AdditionalPropertiesSerializer(beanDesc.getBeanClass(), serializer, mapper);
                        }
                    }
                }
            }
            return serializer;
        }
    });
    return module;
}
 
Example 4
Source File: CoreAppConfig.java    From logsniffer with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Bean
public ObjectMapper jsonObjectMapper() {
	final ObjectMapper jsonMapper = new ObjectMapper();
	jsonMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
	jsonMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
	jsonMapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
	jsonMapper.configure(Feature.ALLOW_SINGLE_QUOTES, true);
	jsonMapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false);

	final SimpleModule module = new SimpleModule("FieldsMapping", Version.unknownVersion());
	module.setSerializerModifier(new BeanSerializerModifier() {
		@Override
		public JsonSerializer<?> modifyMapSerializer(final SerializationConfig config, final MapType valueType,
				final BeanDescription beanDesc, final JsonSerializer<?> serializer) {
			if (FieldsMap.class.isAssignableFrom(valueType.getRawClass())) {
				return new FieldsMapMixInLikeSerializer();
			} else {
				return super.modifyMapSerializer(config, valueType, beanDesc, serializer);
			}
		}
	});
	jsonMapper.registerModule(module);
	return jsonMapper;
}
 
Example 5
Source File: AdminServerWebConfiguration.java    From Moss with Apache License 2.0 5 votes vote down vote up
@Bean
public SimpleModule adminJacksonModule() {
    SimpleModule module = new SimpleModule();
    module.addDeserializer(Registration.class, new RegistrationDeserializer());
    module.setSerializerModifier(new RegistrationBeanSerializerModifier(new SanitizingMapSerializer(
        adminServerProperties.getMetadataKeysToSanitize())));
    return module;
}
 
Example 6
Source File: RegistrationDeserializerTest.java    From Moss with Apache License 2.0 5 votes vote down vote up
public RegistrationDeserializerTest() {
    SimpleModule module = new SimpleModule();
    module.addDeserializer(Registration.class, new RegistrationDeserializer());
    module.setSerializerModifier(
        new RegistrationBeanSerializerModifier(new SanitizingMapSerializer(new String[]{".*password$"})));
    objectMapper = Jackson2ObjectMapperBuilder.json().modules(module).build();
}
 
Example 7
Source File: JacksonDictConfiguration.java    From cola-cloud with MIT License 5 votes vote down vote up
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    if(mappingJackson2HttpMessageConverter != null){
        ObjectMapper objectMapper = mappingJackson2HttpMessageConverter.getObjectMapper();
        SimpleModule module = new SimpleModule("JacksonDictModule");
        JacksonDictJsonModifier jacksonDictJsonModifier = new JacksonDictJsonModifier();
        jacksonDictJsonModifier.setDictClient(dictClient);
        module.setSerializerModifier(jacksonDictJsonModifier);
        objectMapper.registerModule(module);
    }
}
 
Example 8
Source File: DictClient.java    From cola-cloud with MIT License 5 votes vote down vote up
public static void main(String[] args) throws JsonProcessingException {
    ObjectMapper objectMapper = new ObjectMapper();
    SimpleModule module = new SimpleModule();
    module.setSerializerModifier(new JacksonDictJsonModifier());
    DictVO dictItem = new DictVO();
    dictItem.setCode("1231231");
    dictItem.setParent("1231231");
    dictItem.setName("1231231");
    objectMapper.registerModule(module);
    System.out.println(objectMapper.writeValueAsString(dictItem));
}
 
Example 9
Source File: FlatteningSerializer.java    From botbuilder-java with MIT License 5 votes vote down vote up
/**
 * Gets a module wrapping this serializer as an adapter for the Jackson
 * ObjectMapper.
 *
 * @param mapper the object mapper for default serializations
 * @return a simple module to be plugged onto Jackson ObjectMapper.
 */
public static SimpleModule getModule(final ObjectMapper mapper) {
    SimpleModule module = new SimpleModule();
    module.setSerializerModifier(new BeanSerializerModifier() {
        @Override
        public JsonSerializer<?> modifySerializer(SerializationConfig config, BeanDescription beanDesc, JsonSerializer<?> serializer) {
            if (BeanSerializer.class.isAssignableFrom(serializer.getClass())) {
                return new FlatteningSerializer(beanDesc.getBeanClass(), serializer, mapper);
            }
            return serializer;
        }
    });
    return module;
}
 
Example 10
Source File: FlatteningSerializer.java    From autorest-clientruntime-for-java with MIT License 5 votes vote down vote up
/**
 * Gets a module wrapping this serializer as an adapter for the Jackson
 * ObjectMapper.
 *
 * @param mapper the object mapper for default serializations
 * @return a simple module to be plugged onto Jackson ObjectMapper.
 */
public static SimpleModule getModule(final ObjectMapper mapper) {
    SimpleModule module = new SimpleModule();
    module.setSerializerModifier(new BeanSerializerModifier() {
        @Override
        public JsonSerializer<?> modifySerializer(SerializationConfig config, BeanDescription beanDesc, JsonSerializer<?> serializer) {
            if (BeanSerializer.class.isAssignableFrom(serializer.getClass())) {
                return new FlatteningSerializer(beanDesc.getBeanClass(), serializer, mapper);
            }
            return serializer;
        }
    });
    return module;
}
 
Example 11
Source File: DecryptingObjectMapper.java    From halyard with Apache License 2.0 5 votes vote down vote up
public DecryptingObjectMapper(
    SecretSessionManager secretSessionManager,
    Profile profile,
    Path decryptedOutputDirectory,
    boolean decryptAllSecrets) {
  super();
  this.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);
  this.setSerializationInclusion(JsonInclude.Include.NON_NULL);

  this.secretSessionManager = secretSessionManager;
  this.profile = profile;
  this.decryptedOutputDirectory = decryptedOutputDirectory;
  this.decryptAllSecrets = decryptAllSecrets;

  SimpleModule module = new SimpleModule();
  module.setSerializerModifier(
      new BeanSerializerModifier() {

        @Override
        public List<BeanPropertyWriter> changeProperties(
            SerializationConfig config,
            BeanDescription beanDesc,
            List<BeanPropertyWriter> beanProperties) {
          for (BeanPropertyWriter bpw : beanProperties) {
            Secret secret = bpw.getAnnotation(Secret.class);
            if (secret != null && (decryptAllSecrets || secret.alwaysDecrypt())) {
              bpw.assignSerializer(getSecretSerializer());
            }
            SecretFile secretFile = bpw.getAnnotation(SecretFile.class);
            if (secretFile != null) {
              boolean shouldDecrypt = (decryptAllSecrets || secretFile.alwaysDecrypt());
              bpw.assignSerializer(getSecretFileSerializer(bpw, secretFile, shouldDecrypt));
            }
          }
          return beanProperties;
        }
      });
  this.registerModule(module);
}
 
Example 12
Source File: RestTemplateTransportClientFactory.java    From spring-cloud-netflix with Apache License 2.0 5 votes vote down vote up
/**
 * Provides the serialization configurations required by the Eureka Server. JSON
 * content exchanged with eureka requires a root node matching the entity being
 * serialized or deserialized. Achived with
 * {@link SerializationFeature#WRAP_ROOT_VALUE} and
 * {@link DeserializationFeature#UNWRAP_ROOT_VALUE}.
 * {@link PropertyNamingStrategy.SnakeCaseStrategy} is applied to the underlying
 * {@link ObjectMapper}.
 * @return a {@link MappingJackson2HttpMessageConverter} object
 */
public MappingJackson2HttpMessageConverter mappingJacksonHttpMessageConverter() {
	MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
	converter.setObjectMapper(new ObjectMapper()
			.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE));

	SimpleModule jsonModule = new SimpleModule();
	jsonModule.setSerializerModifier(createJsonSerializerModifier()); // keyFormatter,
	// compact));
	converter.getObjectMapper().registerModule(jsonModule);

	converter.getObjectMapper().configure(SerializationFeature.WRAP_ROOT_VALUE, true);
	converter.getObjectMapper().configure(DeserializationFeature.UNWRAP_ROOT_VALUE,
			true);
	converter.getObjectMapper().addMixIn(Applications.class,
			ApplicationsJsonMixIn.class);
	converter.getObjectMapper().addMixIn(InstanceInfo.class,
			InstanceInfoJsonMixIn.class);

	// converter.getObjectMapper().addMixIn(DataCenterInfo.class,
	// DataCenterInfoXmlMixIn.class);
	// converter.getObjectMapper().addMixIn(InstanceInfo.PortWrapper.class,
	// PortWrapperXmlMixIn.class);
	// converter.getObjectMapper().addMixIn(Application.class,
	// ApplicationXmlMixIn.class);
	// converter.getObjectMapper().addMixIn(Applications.class,
	// ApplicationsXmlMixIn.class);

	return converter;
}
 
Example 13
Source File: CallingDefaultSerializerUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenFolder_whenSerializedWithDefaultSerializerStored_NameAndFilesAndDetailsFieldsSerialized() throws IOException {

    SimpleModule module = new SimpleModule();
    module.setSerializerModifier(new FolderBeanSerializerModifier());
    mapper.registerModule(module);

    String json = mapper.writeValueAsString(mockFolder);
    
    HashMap<String, Object> actual = mapper.readValue(json, mapType);

    assertTrue(actual.containsKey("name"));
    assertTrue(actual.containsKey("files"));
    assertEquals(mockFolder.getName(), actual.get("name"));

    List actualFiles = (List) actual.get("files");
    assertEquals(mockFolder.getFiles().size(), actualFiles.size());
    
    Map actualDetails = (Map) actual.get("details");
    assertTrue(actualDetails.containsKey("id"));
    assertTrue(actualDetails.containsKey("name"));
    assertTrue(actualDetails.containsKey("owner"));
    assertTrue(actualDetails.containsKey("created"));
    assertTrue(actualDetails.containsKey("modified"));
    assertTrue(actualDetails.containsKey("lastAccess"));
    
    assertEquals(mockFolder.getId().longValue(), ((Number)actualDetails.get("id")).longValue());
    assertEquals(mockFolder.getName(), actualDetails.get("name"));
    assertEquals(mockFolder.getOwner(), actualDetails.get("owner"));
    assertEquals(mockFolder.getCreated(), new Date((long) actualDetails.get("created")));
    assertEquals(mockFolder.getModified(), new Date((long) actualDetails.get("modified")));
    assertEquals(mockFolder.getLastAccess(), new Date((long) actualDetails.get("lastAccess")));

}
 
Example 14
Source File: DefaultJsonService.java    From imagej-server with Apache License 2.0 4 votes vote down vote up
/**
 * Constructs and initializes a JsonService with an {@link ObjectService}.
 * 
 * @param objectService
 */
public DefaultJsonService(final ObjectService objectService) {

	idToObjDeserializer = new UntypedObjectDeserializer(null, null) {

		@Override
		public Object deserialize(JsonParser p, DeserializationContext ctxt)
			throws IOException, JsonProcessingException
		{
			final Object obj = super.deserialize(p, ctxt);
			if (!(obj instanceof String && ((String) obj).startsWith("object:")))
				return obj;
			final String id = (String) obj;
			if (!objectService.contains(id)) {
				throw new JsonMappingException(p, "Object does not exist");
			}
			final ObjectInfo info = objectService.find(id);
			info.updateLastUsed();
			return info.getObject();
		}
	};

	final JsonSerializer<Object> objToIdSerializer =
		new JsonSerializer<Object>()
	{

			@Override
			public void serialize(Object value, JsonGenerator gen,
				SerializerProvider serializers) throws IOException,
				JsonProcessingException
		{
				gen.writeString(objectService.register(value, "DefaultJsonService"));
			}

		};

	final SimpleModule objToIdModule = new SimpleModule();
	objToIdModule.setSerializerModifier(new BeanSerializerModifier() {

		@Override
		public JsonSerializer<?> modifySerializer(SerializationConfig config,
			BeanDescription beanDesc, JsonSerializer<?> serializer)
		{
			if (Mixins.support(beanDesc.getBeanClass())) return serializer;
			// If the serialized class is unknown (i.e. serialized using the general
			// BeanSerializer) or should not be serialized (i.e. complicated class
			// implemented interfaces such as Iterable), would be serialized as an
			// ID.
			if (serializer instanceof BeanSerializer) return objToIdSerializer;
			if (notSerialized(beanDesc.getBeanClass())) return objToIdSerializer;
			return serializer;

		}
	});
	objToIdMapper = new ObjectMapper();
	objToIdMapper.registerModule(objToIdModule);

	// register Jackson MixIns to obtain better json output format for some
	// specific types
	Mixins.registerMixIns(objToIdMapper);
}