com.fasterxml.jackson.datatype.jsr310.JavaTimeModule Java Examples

The following examples show how to use com.fasterxml.jackson.datatype.jsr310.JavaTimeModule. 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: ObjectMapperContextResolver.java    From microservices-springboot with MIT License 6 votes vote down vote up
private ObjectMapper createObjectMapper() {

        ObjectMapper mapper = new ObjectMapper();

        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);

        mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
        mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

        mapper.registerModule(new Jdk8Module());
        mapper.registerModule(new JavaTimeModule());
        mapper.registerModule(new ParameterNamesModule());

        return mapper;
    }
 
Example #2
Source File: AbstractJpaJerseyTest.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() {
    client = new CrnkClient(getBaseUri().toString());
    client.getObjectMapper().registerModule(new JavaTimeModule());

    JpaModule module = JpaModule.newClientModule();
    client.addModule(module);

    MetaModuleConfig config = new MetaModuleConfig();
    config.addMetaProvider(new ResourceMetaProvider());
    MetaModule clientMetaModule = MetaModule.createServerModule(config);
    client.addModule(clientMetaModule);

    ((MetaLookupImpl) metaModule.getLookup()).initialize();

    setNetworkTimeout(client, 10000, TimeUnit.SECONDS);
}
 
Example #3
Source File: StreamingContextImpl.java    From invest-openapi-java-sdk with Apache License 2.0 6 votes vote down vote up
StreamingContextImpl(@NotNull final OkHttpClient client,
                     @NotNull final String streamingUrl,
                     @NotNull final String authToken,
                     final int streamingParallelism,
                     @NotNull final Logger logger,
                     @NotNull final Executor executor) {
    this.logger = logger;
    this.publisher = new StreamingEventPublisher(executor);
    this.client = client;
    this.mapper = new ObjectMapper();
    this.mapper.registerModule(new JavaTimeModule());
    this.hasStopped = false;

    this.wsClients = new WebSocket[streamingParallelism];
    this.requestsHistory = new ArrayList<>(streamingParallelism);
    this.wsRequest = new okhttp3.Request.Builder().url(streamingUrl).header("Authorization", authToken).build();
    for (int i = 0; i < streamingParallelism; i++) {
        final StreamingApiListener streamingCallback = new StreamingApiListener(i + 1);
        this.wsClients[i] = this.client.newWebSocket(this.wsRequest, streamingCallback);
        this.requestsHistory.add(new HashSet<>());
    }
}
 
Example #4
Source File: ObjectMapperProvider.java    From library with Apache License 2.0 6 votes vote down vote up
/**
 * Constructor...
 */
public ObjectMapperProvider() {
    this.mapper = new ObjectMapper()
            .registerModule(new Jdk8Module())
            .registerModule(new JavaTimeModule())
            .disable(
                    DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES,
                    DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES
            )
            .disable(
                    SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,
                    SerializationFeature.FAIL_ON_EMPTY_BEANS
            )
            .setSerializationInclusion(JsonInclude.Include.NON_NULL)
            .setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
}
 
Example #5
Source File: JacksonAdapter.java    From botbuilder-java with MIT License 6 votes vote down vote up
/**
 * Initializes an instance of JacksonMapperAdapter with default configurations
 * applied to the object mapper.
 *
 * @param mapper the object mapper to use.
 */
private static ObjectMapper initializeObjectMapper(ObjectMapper mapper) {
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
            .configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS, true)
            .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false)
            .configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true)
            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
            .configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true)
            .setSerializationInclusion(JsonInclude.Include.NON_NULL)
            .registerModule(new Jdk8Module())
            .registerModule(new JavaTimeModule())
            .registerModule(new ParameterNamesModule())
            .registerModule(ByteArraySerializer.getModule())
            .registerModule(Base64UrlSerializer.getModule())
            .registerModule(HeadersSerializer.getModule());
    mapper.setVisibility(mapper.getSerializationConfig().getDefaultVisibilityChecker()
            .withFieldVisibility(JsonAutoDetect.Visibility.ANY)
            .withSetterVisibility(JsonAutoDetect.Visibility.NONE)
            .withGetterVisibility(JsonAutoDetect.Visibility.NONE)
            .withIsGetterVisibility(JsonAutoDetect.Visibility.NONE));
    return mapper;
}
 
Example #6
Source File: DockerRegistry.java    From carnotzet with Apache License 2.0 6 votes vote down vote up
private WebTarget getRegistryWebTarget(ImageRef imageRef) {
	if (!webTargets.containsKey(imageRef.getRegistryUrl())) {

		ObjectMapper mapper = new ObjectMapper();
		mapper.registerModule(new JavaTimeModule());

		ClientConfig clientCOnfig = new ClientConfig();
		clientCOnfig.connectorProvider(new HttpUrlConnectorProvider());

		// TODO : This client doesn't handle mandatory Oauth2 Bearer token imposed by some registries implementations (ie : docker hub)
		Client client = ClientBuilder.newClient(clientCOnfig)
				.register(new JacksonJaxbJsonProvider(mapper, new Annotations[] {Annotations.JACKSON}))
				.register(JacksonFeature.class);
		String auth = config.getAuthFor(imageRef.getRegistryName());
		if (auth != null) {
			String[] credentials = new String(Base64.getDecoder().decode(auth), StandardCharsets.UTF_8).split(":");
			client.register(HttpAuthenticationFeature.basicBuilder().credentials(credentials[0], credentials[1]));
		}
		WebTarget webTarget = client.target(imageRef.getRegistryUrl());
		webTargets.put(imageRef.getRegistryUrl(), webTarget);
	}
	return webTargets.get(imageRef.getRegistryUrl());
}
 
Example #7
Source File: BaseContextImpl.java    From invest-openapi-java-sdk with Apache License 2.0 6 votes vote down vote up
public BaseContextImpl(@NotNull final OkHttpClient client,
                       @NotNull final String url,
                       @NotNull final String authToken,
                       @NotNull final Logger logger) {

    this.authToken = authToken;
    this.finalUrl = Objects.requireNonNull(HttpUrl.parse(url))
            .newBuilder()
            .addPathSegment(this.getPath())
            .build();
    this.client = client;
    this.logger = logger;
    this.mapper = new ObjectMapper();

    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.registerModule(new JavaTimeModule());
    mapper.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS);
}
 
Example #8
Source File: ProfileResponseTest.java    From line-bot-sdk-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testProfile() throws IOException {
    try (InputStream resourceAsStream = getSystemResourceAsStream("user-profiles.json")) {
        ObjectMapper objectMapper = new ObjectMapper()
                .registerModule(new JavaTimeModule())
                .configure(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS, false);

        final UserProfileResponse userProfileResponse =
                objectMapper.readValue(resourceAsStream, UserProfileResponse.class);

        assertThat(userProfileResponse.getDisplayName()).isEqualTo("Tester");
        assertThat(userProfileResponse.getUserId()).isEqualTo("Uc6a5e7b3d4d08c33dd8d530fb3c02762");
        assertThat(userProfileResponse.getPictureUrl())
                .isEqualTo(URI.create("https://example.com/picture.png"));
        assertThat(userProfileResponse.getStatusMessage()).isEqualTo("Movie");
    }
}
 
Example #9
Source File: ObjectMapperProvider.java    From jersey-jwt-springsecurity with MIT License 6 votes vote down vote up
private static ObjectMapper createObjectMapper() {

        ObjectMapper mapper = new ObjectMapper();

        mapper.registerModule(new Jdk8Module());
        mapper.registerModule(new JavaTimeModule());
        mapper.registerModule(new ParameterNamesModule());

        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
        mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);

        return mapper;
    }
 
Example #10
Source File: JacksonObjectMapper.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
private static Jackson2ObjectMapperFactory createFactory() {
    return (cls, charset) -> {
        ObjectMapper mapper = new ObjectMapper();
        mapper = new ObjectMapper();
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, false);
        mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
        mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
        mapper.setDateFormat(new RFC3339DateFormat());
        mapper.registerModule(new JavaTimeModule());
        JsonNullableModule jnm = new JsonNullableModule();
        mapper.registerModule(jnm);
        return mapper;
    };
}
 
Example #11
Source File: MonitoringEntry.java    From vind with Apache License 2.0 6 votes vote down vote up
protected static ObjectMapper getMapper(){
    final ObjectMapper objectMapper = new ObjectMapper()
            .configure(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS, false)
            .registerModule(new JavaTimeModule())
            .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
            .addMixIn(Filter.class, FilterMixIn.class)
            .addMixIn(Filter.AndFilter.class, AndFilterMixIn.class)
            .addMixIn(Filter.OrFilter.class, OrFilterMixIn.class)
            .addMixIn(Filter.NotFilter.class, NotFilterMixIn.class)
            .addMixIn(Facet.class, FacetMixin.class)
            .addMixIn(Sort.class, SortMixIn.class)
            .addMixIn(DateMathExpression.class, DateMathExpressionMixIn.class)
            .addMixIn(DateMathExpression.RootTime.class, RootTimeMixIn.class)
            .addMixIn(Interval.ZonedDateTimeInterval.class, ZoneDateIntervalMixin.class)
            .addMixIn(Interval.UtilDateInterval.class, UtilDateIntervalMixin.class)
            .addMixIn(Interval.DateMathInterval.class, DateMathIntervalMixin.class)
            .addMixIn(Facet.DateRangeFacet.class, DateRangeMixin.class)
            .addMixIn(Filter.BetweenDatesFilter.class, BetweenDatesMixIn.class);
    objectMapper.getSerializerProvider().setNullKeySerializer(new MyDtoNullKeySerializer());
    return objectMapper;
}
 
Example #12
Source File: MainApiVerticle.java    From vertx-swagger with Apache License 2.0 6 votes vote down vote up
@Override
public void start(Future<Void> startFuture) throws Exception {
    Json.mapper.registerModule(new JavaTimeModule());
	FileSystem vertxFileSystem = vertx.fileSystem();
    vertxFileSystem.readFile("swagger.json", readFile -> {
        if (readFile.succeeded()) {
            Swagger swagger = new SwaggerParser().parse(readFile.result().toString(Charset.forName("utf-8")));
            SwaggerManager.getInstance().setSwagger(swagger);
            Router swaggerRouter = SwaggerRouter.swaggerRouter(Router.router(vertx), swagger, vertx.eventBus(), new OperationIdServiceIdResolver());
        
            deployVerticles(startFuture);

            vertx.createHttpServer() 
                .requestHandler(swaggerRouter::accept) 
                .listen(config().getInteger("http.port", 8080));
            startFuture.complete();
        } else {
        	startFuture.fail(readFile.cause());
        }
    });        		        
}
 
Example #13
Source File: RestTemplateFakeReactiveHttpClient.java    From feign-reactive with Apache License 2.0 6 votes vote down vote up
RestTemplateFakeReactiveHttpClient(MethodMetadata methodMetadata,
    RestTemplate restTemplate,
    boolean acceptGzip) {
  this.restTemplate = restTemplate;
  this.acceptGzip = acceptGzip;

  ObjectMapper mapper = new ObjectMapper();
  mapper.registerModule(new JavaTimeModule());

  MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
  converter.setObjectMapper(mapper);
  restTemplate.getMessageConverters().add(0, converter);


  final Type returnType = methodMetadata.returnType();
  returnPublisherType = ((ParameterizedType) returnType).getRawType();
  returnActualType = forType(
      resolveLastTypeParameter(returnType, (Class<?>) returnPublisherType));
}
 
Example #14
Source File: MainApiVerticle.java    From swaggy-jenkins with MIT License 6 votes vote down vote up
@Override
public void start(Future<Void> startFuture) throws Exception {
    Json.mapper.registerModule(new JavaTimeModule());
    FileSystem vertxFileSystem = vertx.fileSystem();
    vertxFileSystem.readFile("openapi.json", readFile -> {
        if (readFile.succeeded()) {
            Swagger swagger = new SwaggerParser().parse(readFile.result().toString(Charset.forName("utf-8")));
            Router swaggerRouter = SwaggerRouter.swaggerRouter(router, swagger, vertx.eventBus(), new OperationIdServiceIdResolver());

            deployVerticles(startFuture);

            vertx.createHttpServer()
                .requestHandler(swaggerRouter::accept) 
                .listen(serverPort, h -> {
                    if (h.succeeded()) {
                        startFuture.complete();
                    } else {
                        startFuture.fail(h.cause());
                    }
                });
        } else {
        	startFuture.fail(readFile.cause());
        }
    });        		        
}
 
Example #15
Source File: JsonDBConfig.java    From jsondb-core with MIT License 6 votes vote down vote up
public JsonDBConfig(String dbFilesLocationString, String baseScanPackage,
    ICipher cipher, boolean compatibilityMode, Comparator<String> schemaComparator) {

  this.charset = Charset.forName("UTF-8");
  this.dbFilesLocationString = dbFilesLocationString;
  this.dbFilesLocation = new File(dbFilesLocationString);
  this.dbFilesPath = dbFilesLocation.toPath();
  this.baseScanPackage = baseScanPackage;
  this.cipher = cipher;

  this.compatibilityMode = compatibilityMode;
  this.objectMapper = new ObjectMapper()
          .registerModule(new ParameterNamesModule())
          .registerModule(new Jdk8Module())
          .registerModule(new JavaTimeModule());

  if (compatibilityMode) {
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
  }

  if (null == schemaComparator) {
    this.schemaComparator = new DefaultSchemaVersionComparator();
  } else {
    this.schemaComparator = schemaComparator;
  }
}
 
Example #16
Source File: TestUtil.java    From jhipster-ribbon-hystrix with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Convert an object to JSON byte array.
 *
 * @param object
 *            the object to convert
 * @return the JSON byte array
 * @throws IOException
 */
public static byte[] convertObjectToJsonBytes(Object object)
        throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

    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);
    mapper.registerModule(module);

    return mapper.writeValueAsBytes(object);
}
 
Example #17
Source File: CustomConfig.java    From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
private void setConfigForJdk8(ObjectMapper objectMapper) {
    JavaTimeModule timeModule = new JavaTimeModule();
    timeModule.addSerializer(LocalDate.class,
        new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
    timeModule.addDeserializer(LocalDate.class,
        new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));

    timeModule.addSerializer(Date.class, new DateSerializer());
    timeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(
        DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
    timeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(
        DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
    objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
        .registerModule(timeModule).registerModule(new ParameterNamesModule())
        .registerModule(new Jdk8Module());
}
 
Example #18
Source File: _TestUtil.java    From jhipster-ribbon-hystrix with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Convert an object to JSON byte array.
 *
 * @param object
 *            the object to convert
 * @return the JSON byte array
 * @throws IOException
 */
public static byte[] convertObjectToJsonBytes(Object object)
        throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

    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);
    mapper.registerModule(module);

    return mapper.writeValueAsBytes(object);
}
 
Example #19
Source File: ObjectMapperResolver.java    From clouditor with Apache License 2.0 6 votes vote down vote up
public static void configureObjectMapper(ObjectMapper mapper) {
  mapper.registerModule(new JavaTimeModule());
  mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
  mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
  mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
  mapper.enable(SerializationFeature.INDENT_OUTPUT);
  mapper.setSerializationInclusion(Include.NON_NULL);
  mapper.setConfig(mapper.getSerializationConfig().withView(ApiOnly.class));

  // add all sub types of CloudAccount
  for (var type : REFLECTIONS_SUBTYPE_SCANNER.getSubTypesOf(CloudAccount.class)) {
    mapper.registerSubtypes(type);
  }

  // set injectable value to null
  var values = new InjectableValues.Std();
  values.addValue("hash", null);

  mapper.setInjectableValues(values);
}
 
Example #20
Source File: TestUtil.java    From jhipster-ribbon-hystrix with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Convert an object to JSON byte array.
 *
 * @param object
 *            the object to convert
 * @return the JSON byte array
 * @throws IOException
 */
public static byte[] convertObjectToJsonBytes(Object object)
        throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

    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);
    mapper.registerModule(module);

    return mapper.writeValueAsBytes(object);
}
 
Example #21
Source File: JacksonModule.java    From proteus with Apache License 2.0 6 votes vote down vote up
@Override
protected void configure()
{
    ObjectMapper objectMapper = new ObjectMapper();

    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT, true);
    objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
    objectMapper.configure(DeserializationFeature.EAGER_DESERIALIZER_FETCH, true);
    objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
    objectMapper.configure(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS, true);

    objectMapper.registerModule(new AfterburnerModule());
    objectMapper.registerModule(new Jdk8Module());
    objectMapper.registerModule(new JavaTimeModule());
    objectMapper.registerModule(new ParameterNamesModule());

    this.bind(ObjectMapper.class).toInstance(objectMapper);
}
 
Example #22
Source File: TestUtil.java    From jhipster-microservices-example with Apache License 2.0 5 votes vote down vote up
/**
 * Convert an object to JSON byte array.
 *
 * @param object
 *            the object to convert
 * @return the JSON byte array
 * @throws IOException
 */
public static byte[] convertObjectToJsonBytes(Object object)
        throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

    JavaTimeModule module = new JavaTimeModule();
    mapper.registerModule(module);

    return mapper.writeValueAsBytes(object);
}
 
Example #23
Source File: TestUtil.java    From jhipster-online with Apache License 2.0 5 votes vote down vote up
private static ObjectMapper createObjectMapper() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.WRITE_DURATIONS_AS_TIMESTAMPS, false);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
    mapper.registerModule(new JavaTimeModule());
    return mapper;
}
 
Example #24
Source File: NewRelicClient.java    From newrelic-alerts-configurator with Apache License 2.0 5 votes vote down vote up
private JacksonJsonProvider createMapper() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.configure(ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
    mapper.setSerializationInclusion(NON_NULL);
    mapper.registerModule(new Jdk8Module());
    mapper.registerModule(new JavaTimeModule());
    return new JacksonJaxbJsonProvider(mapper, DEFAULT_ANNOTATIONS);
}
 
Example #25
Source File: JSON.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
public JSON() {
  mapper = new ObjectMapper();
  mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
  mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
  mapper.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, false);
  mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
  mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
  mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
  mapper.setDateFormat(new RFC3339DateFormat());
  mapper.registerModule(new JavaTimeModule());
  mapper.registerModule(new JodaModule());
}
 
Example #26
Source File: JacksonConfiguration.java    From celerio-angular-quickstart with Apache License 2.0 5 votes vote down vote up
@Bean
Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder() {
    JavaTimeModule module = new JavaTimeModule();

    module.addDeserializer(LocalDate.class, new CustomLocalDateDeserializer());
    module.addSerializer(LocalDate.class, new CustomLocalDateSerializer());

    module.addDeserializer(LocalDateTime.class, new CustomLocalDateTimeDeserializer());
    module.addSerializer(LocalDateTime.class, new CustomLocalDateTimeSerializer());

    return new Jackson2ObjectMapperBuilder().featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS).findModulesViaServiceLoader(true)
            .modulesToInstall(module);
}
 
Example #27
Source File: ObjectMapperConstructor.java    From n2o-framework with Apache License 2.0 5 votes vote down vote up
public static ObjectMapper metaObjectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setDateFormat(new SimpleDateFormat(DomainProcessor.JAVA_DATE_FORMAT));
//        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
//        objectMapper.setVisibility(objectMapper.getSerializationConfig().getDefaultVisibilityChecker()
//                .withFieldVisibility(JsonAutoDetect.Visibility.NONE)
//                .withGetterVisibility(JsonAutoDetect.Visibility.NONE)
//                .withSetterVisibility(JsonAutoDetect.Visibility.NONE)
//                .withCreatorVisibility(JsonAutoDetect.Visibility.NONE)
//                .withIsGetterVisibility(JsonAutoDetect.Visibility.NONE));
        objectMapper.registerModule(new JavaTimeModule());
        objectMapper.registerModule(new N2oJacksonModule(new SimpleDateFormat(DomainProcessor.JAVA_DATE_FORMAT)));
        return objectMapper;
    }
 
Example #28
Source File: FilterObjectMapperBuilder.java    From jfilter with Apache License 2.0 5 votes vote down vote up
/**
 * Build configured ObjectMapper
 *
 * @return {@link ObjectMapper}
 */
public ObjectMapper build() {

    //Add mixin filter if filterFields isn't null and has filterable fields
    if(filterFields != null && filterFields.getFieldsMap().size() > 0) {
        objectMapper.addMixIn(Object.class, MixinFilter.class);
        objectMapper.setFilterProvider(new SimpleFilterProvider()
                .addFilter("com.jfilter.converter.MixinFilter", new MixinFilter(filterFields)));
    }

    //Set dateTimeModule if option is enabled
    if (serializationConfig.isDateTimeModuleEnabled()) {
        //Add JavaTimeModule to fix issue with LocalDate/LocalDateTime serialization
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        javaTimeModule.addSerializer(LocalTime.class, LocalTimeSerializer.INSTANCE);
        javaTimeModule.addSerializer(LocalDate.class, LocalDateSerializer.INSTANCE);
        javaTimeModule.addSerializer(LocalDateTime.class, LocalDateTimeSerializer.INSTANCE);
        javaTimeModule.addDeserializer(LocalTime.class, LocalTimeDeserializer.INSTANCE);
        javaTimeModule.addDeserializer(LocalDate.class, LocalDateDeserializer.INSTANCE);
        javaTimeModule.addDeserializer(LocalDateTime.class, LocalDateTimeDeserializer.INSTANCE);
        objectMapper.registerModule(javaTimeModule);
        objectMapper.registerModule(new Jdk8Module());
        objectMapper.findAndRegisterModules();
    }

    return objectMapper;
}
 
Example #29
Source File: URIImagemapActionTest.java    From line-bot-sdk-java with Apache License 2.0 5 votes vote down vote up
@Test
public void getLinkUri() throws Exception {
    URIImagemapAction imageMapAction = new URIImagemapAction("http://example.com",
                                                             new ImagemapArea(1, 2, 3, 4));

    ObjectMapper objectMapper = new ObjectMapper()
            .registerModule(new JavaTimeModule())
            .configure(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS, false);
    String s = objectMapper.writeValueAsString(imageMapAction);
    assertThat(s).contains("\"type\":\"uri\"");
}
 
Example #30
Source File: ObjectMapperBeanEventListener.java    From micronaut-microservices-poc with Apache License 2.0 5 votes vote down vote up
@Override
public ObjectMapper onCreated(BeanCreatedEvent<ObjectMapper> event) {
    final ObjectMapper mapper = event.getBean();
    mapper.registerModule(new JavaTimeModule());
    mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    return mapper;
}