org.springframework.http.converter.json.Jackson2ObjectMapperBuilder Java Examples

The following examples show how to use org.springframework.http.converter.json.Jackson2ObjectMapperBuilder. 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: JacksonConfig.java    From xmall with MIT License 7 votes vote down vote up
@Bean
    @Primary
    @ConditionalOnMissingBean(ObjectMapper.class)
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();

        // 通过该方法对mapper对象进行设置,所有序列化的对象都将按改规则进行系列化
        // Include.Include.ALWAYS 默认
        // Include.NON_DEFAULT 属性为默认值不序列化
        // Include.NON_EMPTY 属性为 空("") 或者为 NULL 都不序列化,则返回的json是没有这个字段的。这样对移动端会更省流量
        // Include.NON_NULL 属性为NULL 不序列化,就是为null的字段不参加序列化
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

        // 字段保留,将null值转为""
//        objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>()
//        {
//            @Override
//            public void serialize(Object o, JsonGenerator jsonGenerator,
//                                  SerializerProvider serializerProvider)
//                    throws IOException, JsonProcessingException
//            {
//                jsonGenerator.writeString("");
//            }
//        });
        return objectMapper;
    }
 
Example #2
Source File: JacksonConfig.java    From macrozheng with Apache License 2.0 6 votes vote down vote up
@Bean
    @Primary
    @ConditionalOnMissingBean(ObjectMapper.class)
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();

        // 通过该方法对mapper对象进行设置,所有序列化的对象都将按改规则进行系列化
        // Include.Include.ALWAYS 默认
        // Include.NON_DEFAULT 属性为默认值不序列化
        // Include.NON_EMPTY 属性为 空("") 或者为 NULL 都不序列化,则返回的json是没有这个字段的。这样对移动端会更省流量
        // Include.NON_NULL 属性为NULL 不序列化,就是为null的字段不参加序列化
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

        // 字段保留,将null值转为""
//        objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>()
//        {
//            @Override
//            public void serialize(Object o, JsonGenerator jsonGenerator,
//                                  SerializerProvider serializerProvider)
//                    throws IOException, JsonProcessingException
//            {
//                jsonGenerator.writeString("");
//            }
//        });
        return objectMapper;
    }
 
Example #3
Source File: DashboardConfigService.java    From find with MIT License 6 votes vote down vote up
@Autowired
public DashboardConfigService(final JsonDeserializer<TagName> tagNameDeserializer) {
    super(
        "dashboards.json",
        "defaultDashboardsConfigFile.json",
        DashboardConfig.class,
        DashboardConfig.builder().build(),
        new Jackson2ObjectMapperBuilder()
            .mixIn(Widget.class, WidgetMixins.class)
            .mixIn(WidgetDatasource.class, WidgetDatasourceMixins.class)
            .deserializersByType(ImmutableMap.of(TagName.class, tagNameDeserializer))
            .serializersByType(ImmutableMap.of(TagName.class, new TagNameSerializer()))
            .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,
                               DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE)
    );
}
 
Example #4
Source File: Project.java    From citrus-admin with Apache License 2.0 6 votes vote down vote up
/**
 * Load settings from project info file.
 */
public void loadSettings() {
    try (FileInputStream fileInput = new FileInputStream(getProjectInfoFile())) {
        String projectInfo = FileUtils.readToString(fileInput);

        // support legacy build configuration
        projectInfo = projectInfo.replaceAll("com\\.consol\\.citrus\\.admin\\.model\\.build\\.maven\\.MavenBuildConfiguration", MavenBuildContext.class.getName());

        Project project = Jackson2ObjectMapperBuilder.json().build().readerFor(Project.class).readValue(projectInfo);

        setName(project.getName());
        setDescription(project.getDescription());
        setSettings(project.getSettings());
        setVersion(project.getVersion());
    } catch (IOException e) {
        throw new CitrusRuntimeException("Failed to read project settings file", e);
    }
}
 
Example #5
Source File: MvcConfig.java    From tutorials with MIT License 6 votes vote down vote up
@Override
public void configureMessageConverters(final List<HttpMessageConverter<?>> messageConverters) {
    final Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
    builder.indentOutput(true)
        .dateFormat(new SimpleDateFormat("dd-MM-yyyy hh:mm"));
    messageConverters.add(new MappingJackson2HttpMessageConverter(builder.build()));
    messageConverters.add(new MappingJackson2XmlHttpMessageConverter(builder.createXmlMapper(true)
        .build()));

    messageConverters.add(createXmlHttpMessageConverter());
    // messageConverters.add(new MappingJackson2HttpMessageConverter());

    messageConverters.add(new ProtobufHttpMessageConverter());
    messageConverters.add(new KryoHttpMessageConverter());
    messageConverters.add(new StringHttpMessageConverter());
}
 
Example #6
Source File: ManagementConfiguration.java    From Spring-Boot-2.0-Cookbook-Second-Edition with MIT License 6 votes vote down vote up
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.
            json().
            //propertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE).
            propertyNamingStrategy(PropertyNamingStrategy.LOWER_CAMEL_CASE).
            //featuresToEnable(SerializationFeature.INDENT_OUTPUT).
            //featuresToEnable(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY).
            build();
    SimpleModule module = new SimpleModule();
    module.addSerializer(Set.class,
            new StdDelegatingSerializer(Set.class, new StdConverter<Set, List>() {
                @Override
                public List convert(Set value) {
                    LinkedList list = new LinkedList(value);
                    Collections.sort(list);
                    return list;
                }
            })
    );
    objectMapper.registerModule(module);
    HttpMessageConverter c = new MappingJackson2HttpMessageConverter(
            objectMapper
    );
    converters.add(c);
}
 
Example #7
Source File: ManagementConfiguration.java    From Spring-Boot-2.0-Cookbook-Second-Edition with MIT License 6 votes vote down vote up
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.
            json().
            //propertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE).
            propertyNamingStrategy(PropertyNamingStrategy.LOWER_CAMEL_CASE).
            //featuresToEnable(SerializationFeature.INDENT_OUTPUT).
            //featuresToEnable(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY).
            build();
    SimpleModule module = new SimpleModule();
    module.addSerializer(Set.class,
            new StdDelegatingSerializer(Set.class, new StdConverter<Set, List>() {
                @Override
                public List convert(Set value) {
                    LinkedList list = new LinkedList(value);
                    Collections.sort(list);
                    return list;
                }
            })
    );
    objectMapper.registerModule(module);
    HttpMessageConverter c = new MappingJackson2HttpMessageConverter(
            objectMapper
    );
    converters.add(c);
}
 
Example #8
Source File: JacksonConfig.java    From dts-shop with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
public Jackson2ObjectMapperBuilderCustomizer customJackson() {
	return new Jackson2ObjectMapperBuilderCustomizer() {
		@Override
		public void customize(Jackson2ObjectMapperBuilder builder) {
			builder.serializerByType(LocalDateTime.class,
					new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
			builder.serializerByType(LocalDate.class,
					new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
			builder.serializerByType(LocalTime.class,
					new LocalTimeSerializer(DateTimeFormatter.ofPattern("HH:mm:ss")));

			builder.deserializerByType(LocalDateTime.class,
					new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
			builder.deserializerByType(LocalDate.class,
					new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
			builder.deserializerByType(LocalTime.class,
					new LocalTimeDeserializer(DateTimeFormatter.ofPattern("HH:mm:ss")));
			builder.serializationInclusion(JsonInclude.Include.NON_NULL);
			builder.failOnUnknownProperties(false);
			builder.featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
		}
	};
}
 
Example #9
Source File: ApplicationTests.java    From oauth2-client with MIT License 6 votes vote down vote up
@Ignore
@Test
public void contextLoads() {

    //用登陆后的token ,请求api资源
    //header格式,Authorization : Bearer xxxxx

    RestTemplate restTemplate = new RestTemplate();
    JavaTimeModule module = new JavaTimeModule();
    LocalDateTimeDeserializer localDateTimeDeserializer = new LocalDateTimeDeserializer(
        DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    module.addDeserializer(LocalDateTime.class, localDateTimeDeserializer);

    ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().modules(module)
        .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS).build();

    MappingJackson2HttpMessageConverter jsonMessageConverter = new MappingJackson2HttpMessageConverter();
    jsonMessageConverter.setObjectMapper(objectMapper);
    restTemplate.getMessageConverters().add(0, jsonMessageConverter);

    // request some api


}
 
Example #10
Source File: JacksonConfig.java    From macrozheng-mall with MIT License 6 votes vote down vote up
@Bean
    @Primary
    @ConditionalOnMissingBean(ObjectMapper.class)
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();

        // 通过该方法对mapper对象进行设置,所有序列化的对象都将按改规则进行系列化
        // Include.Include.ALWAYS 默认
        // Include.NON_DEFAULT 属性为默认值不序列化
        // Include.NON_EMPTY 属性为 空("") 或者为 NULL 都不序列化,则返回的json是没有这个字段的。这样对移动端会更省流量
        // Include.NON_NULL 属性为NULL 不序列化,就是为null的字段不参加序列化
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

        // 字段保留,将null值转为""
//        objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>()
//        {
//            @Override
//            public void serialize(Object o, JsonGenerator jsonGenerator,
//                                  SerializerProvider serializerProvider)
//                    throws IOException, JsonProcessingException
//            {
//                jsonGenerator.writeString("");
//            }
//        });
        return objectMapper;
    }
 
Example #11
Source File: CustomizationConfigService.java    From find with MIT License 6 votes vote down vote up
protected CustomizationConfigService(
    final String configFileName,
    final String defaultFileName,
    final Class<T> configClass,
    final T emptyConfig,
    final Jackson2ObjectMapperBuilder objectMapperBuilder
) {
    this.configClass = configClass;
    this.emptyConfig = emptyConfig;

    final ObjectMapper objectMapper = objectMapperBuilder
        .featuresToEnable(SerializationFeature.INDENT_OUTPUT)
        .createXmlMapper(false)
        .build();

    setMapper(objectMapper);
    setConfigFileLocation(FindConfigFileService.CONFIG_FILE_LOCATION);
    setDeprecatedConfigFileLocations(Collections.singletonList(CONFIG_FILE_LOCATION_HP));
    setConfigFileName(Paths.get(CONFIG_DIRECTORY).resolve(configFileName).toString());
    setDefaultConfigFile('/' + defaultFileName);
}
 
Example #12
Source File: JacksonConfig.java    From mall-swarm with Apache License 2.0 6 votes vote down vote up
@Bean
    @Primary
    @ConditionalOnMissingBean(ObjectMapper.class)
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();

        // 通过该方法对mapper对象进行设置,所有序列化的对象都将按改规则进行系列化
        // Include.Include.ALWAYS 默认
        // Include.NON_DEFAULT 属性为默认值不序列化
        // Include.NON_EMPTY 属性为 空("") 或者为 NULL 都不序列化,则返回的json是没有这个字段的。这样对移动端会更省流量
        // Include.NON_NULL 属性为NULL 不序列化,就是为null的字段不参加序列化
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

        // 字段保留,将null值转为""
//        objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>()
//        {
//            @Override
//            public void serialize(Object o, JsonGenerator jsonGenerator,
//                                  SerializerProvider serializerProvider)
//                    throws IOException, JsonProcessingException
//            {
//                jsonGenerator.writeString("");
//            }
//        });
        return objectMapper;
    }
 
Example #13
Source File: WebConfiguration.java    From library with MIT License 5 votes vote down vote up
private void postProcessHalObjectMapper(ObjectMapper objectMapper) {
    try {
        Jackson2ObjectMapperBuilder builder = this.beanFactory.getBean(Jackson2ObjectMapperBuilder.class);
        builder.configure(objectMapper);
    } catch (NoSuchBeanDefinitionException ex) {
        // No Jackson configuration required
    }
}
 
Example #14
Source File: JacksonConfiguration.java    From klask-io with GNU General Public License v3.0 5 votes vote down vote up
@Bean
Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder() {
    JavaTimeModule module = new JavaTimeModule();
    module.addSerializer(OffsetDateTime.class, JSR310DateTimeSerializer.INSTANCE);
    module.addSerializer(ZonedDateTime.class, JSR310DateTimeSerializer.INSTANCE);
    module.addSerializer(LocalDateTime.class, JSR310DateTimeSerializer.INSTANCE);
    module.addSerializer(Instant.class, JSR310DateTimeSerializer.INSTANCE);
    module.addDeserializer(LocalDate.class, JSR310LocalDateDeserializer.INSTANCE);
    return new Jackson2ObjectMapperBuilder()
            .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
            .findModulesViaServiceLoader(true)
            .modulesToInstall(module);
}
 
Example #15
Source File: JacksonConfig.java    From joal with Apache License 2.0 5 votes vote down vote up
@Bean
public Jackson2ObjectMapperBuilder objectMapperBuilder() {
    return new Jackson2ObjectMapperBuilder()
            .featuresToDisable(
                    SerializationFeature.WRITE_DATES_AS_TIMESTAMPS
            )
            .failOnEmptyBeans(false)
            .serializers(
                    new InfoHashSerializer(),
                    new LocalDateTimeSerializer()
            );
}
 
Example #16
Source File: OpenAPIUiConfiguration.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Bean
public Jackson2ObjectMapperBuilder builder() {
  return new Jackson2ObjectMapperBuilder()
      .indentOutput(true)
      .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
      .modulesToInstall(new JsonNullableModule())
      .dateFormat(new RFC3339DateFormat());
}
 
Example #17
Source File: VaadinConnectControllerTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void should_NotOverrideVisibility_When_JacksonPropertiesProvideVisibility() {
    ApplicationContext contextMock = mock(ApplicationContext.class);
    ObjectMapper mockDefaultObjectMapper = mock(ObjectMapper.class);
    ObjectMapper mockOwnObjectMapper = mock(ObjectMapper.class);
    Jackson2ObjectMapperBuilder mockObjectMapperBuilder = mock(Jackson2ObjectMapperBuilder.class);
    JacksonProperties mockJacksonProperties = mock(JacksonProperties.class);
    when(contextMock.getBean(ObjectMapper.class))
            .thenReturn(mockDefaultObjectMapper);
    when(contextMock.getBean(JacksonProperties.class))
            .thenReturn(mockJacksonProperties);
    when(contextMock.getBean(Jackson2ObjectMapperBuilder.class))
            .thenReturn(mockObjectMapperBuilder);
    when(mockObjectMapperBuilder.createXmlMapper(false))
            .thenReturn(mockObjectMapperBuilder);
    when(mockObjectMapperBuilder.build())
            .thenReturn(mockOwnObjectMapper);
    when(mockJacksonProperties.getVisibility())
            .thenReturn(Collections.singletonMap(PropertyAccessor.ALL,
                    JsonAutoDetect.Visibility.PUBLIC_ONLY));
    new VaadinConnectController(null,
            mock(VaadinConnectAccessChecker.class),
            mock(EndpointNameChecker.class),
            mock(ExplicitNullableTypeChecker.class),
            contextMock,
            mock(ServletContext.class));

    verify(contextMock, never()).getBean(ObjectMapper.class);
    verify(contextMock, times(1)).getBean(Jackson2ObjectMapperBuilder.class);
    verify(mockDefaultObjectMapper, never()).setVisibility(
            PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    verify(mockOwnObjectMapper, never()).setVisibility(
            PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    verify(contextMock, times(1)).getBean(JacksonProperties.class);
}
 
Example #18
Source File: OpenAPIUiConfiguration.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Bean
public Jackson2ObjectMapperBuilder builder() {
  return new Jackson2ObjectMapperBuilder()
      .indentOutput(true)
      .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
      .modulesToInstall(new JsonNullableModule())
      .dateFormat(new RFC3339DateFormat());
}
 
Example #19
Source File: VaadinConnectController.java    From flow with Apache License 2.0 5 votes vote down vote up
private ObjectMapper createVaadinConnectObjectMapper(ApplicationContext context) {
  Jackson2ObjectMapperBuilder builder = context.getBean(Jackson2ObjectMapperBuilder.class);
  ObjectMapper objectMapper = builder.createXmlMapper(false).build();
  JacksonProperties jacksonProperties = context
          .getBean(JacksonProperties.class);
  if (jacksonProperties.getVisibility().isEmpty()) {
      objectMapper.setVisibility(PropertyAccessor.ALL,
              JsonAutoDetect.Visibility.ANY);
  }
  return objectMapper;
}
 
Example #20
Source File: WebMvcConfig.java    From spring-http-patch-example with GNU General Public License v3.0 5 votes vote down vote up
@Bean
public Jackson2ObjectMapperBuilder jacksonBuilder() {

    Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
    builder
            .serializerByType(ZonedDateTime.class, ZonedDateTimeSerializer.INSTANCE)
            .deserializerByType(ZonedDateTime.class, ZONED_DATE_TIME)
            .applicationContext(applicationContext);
    return builder;
}
 
Example #21
Source File: FederationsAdminControllerTest.java    From waggle-dance with Apache License 2.0 5 votes vote down vote up
@Test
public void add() throws Exception {
  String content = Jackson2ObjectMapperBuilder.json().build().writeValueAsString(metastore);
  mockMvc
      .perform(post("/api/admin/federations/").contentType(MediaType.APPLICATION_JSON_UTF8).content(content))
      .andExpect(status().isOk());
  verify(populateStatusFederationService).register(metastore);
}
 
Example #22
Source File: ProjectService.java    From citrus-admin with Apache License 2.0 5 votes vote down vote up
/**
 * Save project information to file system.
 * @param project
 */
public void saveProjectInfo(Project project) {
    try (FileOutputStream fos = new FileOutputStream(project.getProjectInfoFile())) {
        fos.write(Jackson2ObjectMapperBuilder.json().build().writer().withDefaultPrettyPrinter().writeValueAsBytes(project));
        fos.flush();
    } catch (IOException e) {
        throw new CitrusRuntimeException("Unable to open project info file", e);
    }
}
 
Example #23
Source File: MvcConfig.java    From tutorials with MIT License 5 votes vote down vote up
@Override
public void configureMessageConverters(final List<HttpMessageConverter<?>> messageConverters) {
    final Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
    builder.indentOutput(true)
        .dateFormat(new SimpleDateFormat("dd-MM-yyyy hh:mm"));

}
 
Example #24
Source File: JacksonConfiguration.java    From OpenIoE with Apache License 2.0 5 votes vote down vote up
@Bean
Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder() {
    JavaTimeModule module = new JavaTimeModule();
    module.addSerializer(OffsetDateTime.class, JSR310DateTimeSerializer.INSTANCE);
    module.addSerializer(ZonedDateTime.class, JSR310DateTimeSerializer.INSTANCE);
    module.addSerializer(LocalDateTime.class, JSR310DateTimeSerializer.INSTANCE);
    module.addSerializer(Instant.class, JSR310DateTimeSerializer.INSTANCE);
    module.addDeserializer(LocalDate.class, JSR310LocalDateDeserializer.INSTANCE);
    return new Jackson2ObjectMapperBuilder()
            .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
            .findModulesViaServiceLoader(true)
            .modulesToInstall(module);
}
 
Example #25
Source File: MainApp.java    From botanic-ng with Apache License 2.0 5 votes vote down vote up
@Bean
public Jackson2ObjectMapperBuilderCustomizer addCustomBigDecimalDeserialization() {
	return new Jackson2ObjectMapperBuilderCustomizer() {

		@Override
		public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {
			jacksonObjectMapperBuilder.dateFormat(new ISO8601DateFormatWithMilliSeconds());
		}

	};
}
 
Example #26
Source File: MainController.java    From steady with Apache License 2.0 5 votes vote down vote up
/**
	 * Can be used to do some initialization at application startup, but does not do anything right now.
	 *
	 * @return a {@link org.springframework.http.converter.json.Jackson2ObjectMapperBuilder} object.
	 */
//	@Bean
//	CommandLineRunner init() { return null; }

	@Bean
	public Jackson2ObjectMapperBuilder jacksonBuilder() {
	    Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
	    builder.defaultViewInclusion(true);
	    //builder.indentOutput(true).dateFormat(new SimpleDateFormat("yyyy-MM-dd"));
	    return builder;
	}
 
Example #27
Source File: JacksonConfiguration.java    From jhipster-ribbon-hystrix with GNU General Public License v3.0 5 votes vote down vote up
@Bean
Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder() {
    JavaTimeModule module = new JavaTimeModule();
    module.addSerializer(OffsetDateTime.class, JSR310DateTimeSerializer.INSTANCE);
    module.addSerializer(ZonedDateTime.class, JSR310DateTimeSerializer.INSTANCE);
    module.addSerializer(LocalDateTime.class, JSR310DateTimeSerializer.INSTANCE);
    module.addSerializer(Instant.class, JSR310DateTimeSerializer.INSTANCE);
    module.addDeserializer(LocalDate.class, JSR310LocalDateDeserializer.INSTANCE);
    return new Jackson2ObjectMapperBuilder()
            .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
            .findModulesViaServiceLoader(true)
            .modulesToInstall(module);
}
 
Example #28
Source File: JacksonConfig.java    From bearchoke with Apache License 2.0 5 votes vote down vote up
@Bean
    public ObjectMapper objectMapper() {
        Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();

        builder.featuresToDisable(
                SerializationFeature.WRITE_DATES_AS_TIMESTAMPS
        );

        builder.featuresToEnable(
                SerializationFeature.WRITE_DATES_WITH_ZONE_ID,
//                SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,
//                SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS,
//                DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS,
                DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT
        );

        builder.indentOutput(true);

        builder.failOnEmptyBeans(false);
        builder.failOnUnknownProperties(false);

        // do not include null value in json to make object graph smaller
        builder.serializationInclusion(JsonInclude.Include.NON_NULL);

        builder.modules(new GeoJsonModule(), new JavaTimeModule(), new MoneyModule());

        return builder.build();
    }
 
Example #29
Source File: WebSocketMessageBrokerConfigurationSupport.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
protected MappingJackson2MessageConverter createJacksonConverter() {
	MappingJackson2MessageConverter messageConverter = super.createJacksonConverter();
	// Use Jackson builder in order to have JSR-310 and Joda-Time modules registered automatically
	Jackson2ObjectMapperBuilder builder = Jackson2ObjectMapperBuilder.json();
	ApplicationContext applicationContext = getApplicationContext();
	if (applicationContext != null) {
		builder.applicationContext(applicationContext);
	}
	messageConverter.setObjectMapper(builder.build());
	return messageConverter;
}
 
Example #30
Source File: Application.java    From spring-jackson-demo with Apache License 2.0 5 votes vote down vote up
@Bean
public Jackson2ObjectMapperBuilder jacksonBuilder() {
	Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
	builder.indentOutput(true);
	builder.dateFormat(new SimpleDateFormat("yyyy-MM-dd"));
	return builder;
}