Java Code Examples for com.fasterxml.jackson.databind.ObjectMapper#setDateFormat()

The following examples show how to use com.fasterxml.jackson.databind.ObjectMapper#setDateFormat() . 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: DatabaseClientSingleton.java    From java-client-api with Apache License 2.0 6 votes vote down vote up
private static void registerHandlers() {
  if ( handlesRegistered == true ) return;
  try {
  DatabaseClientFactory.getHandleRegistry().register(
    JAXBHandle.newFactory(ProductDetails.class));
  } catch (JAXBException e) {
    throw new IllegalStateException(e);
  }
  ObjectMapper mapper = new JacksonDatabindHandle(null).getMapper();
  // we do the next three lines so dates are written in xs:dateTime format
  // which makes them ready for range indexes in MarkLogic Server
  String ISO_8601_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";
  mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
  mapper.setDateFormat(new SimpleDateFormat(ISO_8601_FORMAT));
  DatabaseClientFactory.getHandleRegistry().register(
    JacksonDatabindHandle.newFactory(mapper, Employee.class));
  DatabaseClientFactory.getHandleRegistry().register(
    JacksonDatabindHandle.newFactory(mapper, LoadDetail.class));
  handlesRegistered = true;
}
 
Example 2
Source File: JsonUtils.java    From knox with Apache License 2.0 6 votes vote down vote up
public static String renderAsJsonString(Object obj, FilterProvider filterProvider, DateFormat dateFormat) {
  String json = null;
  ObjectMapper mapper = new ObjectMapper();
  if (filterProvider != null) {
    mapper.setFilterProvider(filterProvider);
  }

  if (dateFormat != null) {
    mapper.setDateFormat(dateFormat);
  }

  try {
    // write JSON to a file
    json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
  } catch ( JsonProcessingException e ) {
    LOG.failedToSerializeObjectToJSON( obj, e );
  }
  return json;
}
 
Example 3
Source File: JacksonConfigurator.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
public static ObjectMapper configureObjectMapper(ObjectMapper mapper) {
  SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormatString);
  mapper.setDateFormat(dateFormat);
  mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
  mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

  return mapper;
}
 
Example 4
Source File: N2oEngineConfiguration.java    From n2o-framework with Apache License 2.0 5 votes vote down vote up
private ObjectMapper restObjectMapper() {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setDateFormat(new SimpleDateFormat(serializingFormat));
    RestEngineTimeModule module = new RestEngineTimeModule(deserializingFormats, exclusionKeys);
    objectMapper.registerModules(module);
    return objectMapper;
}
 
Example 5
Source File: PolicyImporter.java    From opsgenie-configuration-backup with Apache License 2.0 5 votes vote down vote up
private PolicyWithTeamInfo readJson(String policyJson) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new JodaModule());
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    mapper.setDateFormat(sdf);
    return mapper.readValue(policyJson, PolicyWithTeamInfo.class);
}
 
Example 6
Source File: JsonMapper.java    From spring-boot-ddd with GNU General Public License v3.0 5 votes vote down vote up
public JsonMapper() {
    MAPPER = new ObjectMapper();
    MAPPER.registerModule(new JavaTimeModule());
    MAPPER.registerModule(new Jdk8Module());
    MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    MAPPER.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
}
 
Example 7
Source File: ApiClient.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
/**
 * Set the date format used to parse/format date parameters.
 * @param dateFormat Date format
 * @return API client
 */
public ApiClient setDateFormat(DateFormat dateFormat) {
    this.dateFormat = dateFormat;
    for(HttpMessageConverter converter:restTemplate.getMessageConverters()){
        if(converter instanceof AbstractJackson2HttpMessageConverter){
            ObjectMapper mapper = ((AbstractJackson2HttpMessageConverter)converter).getObjectMapper();
            mapper.setDateFormat(dateFormat);
        }
    }
    return this;
}
 
Example 8
Source File: MongoEventRepositoryTest.java    From OpenLRW with Educational Community License v2.0 5 votes vote down vote up
@Before
public void init() throws JsonParseException, JsonMappingException, UnsupportedEncodingException, IOException {
  ObjectMapper mapper = new ObjectMapper();
  mapper.findAndRegisterModules();
  mapper.setDateFormat(new ISO8601DateFormat());

  Envelope envelope = mapper.readValue(MediaEventTest.MEDIA_EVENT.getBytes("UTF-8"), Envelope.class);
  mediaEvent = envelope.getData().get(0);
}
 
Example 9
Source File: JasonConfig.java    From springboot-plus with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean(ObjectMapper.class)
public ObjectMapper getObjectMapper() {
	ObjectMapper objectMapper = new ObjectMapper();
	objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
	objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
	SimpleModule simpleModule = new SimpleModule("SimpleModule", 
			Version.unknownVersion());
	simpleModule.addSerializer(JsonResult.class, new CustomJsonResultSerializer());
	objectMapper.registerModule(simpleModule);
	return objectMapper;
}
 
Example 10
Source File: SubscriptionJsonTest.java    From emodb with Apache License 2.0 5 votes vote down vote up
@Test
public void testSubscriptionJson() throws Exception {
    Date now = new Date();
    String nowString = DateTimeFormatter.ISO_INSTANT.withZone(ZoneOffset.UTC).format(now.toInstant());

    Subscription expected = new DefaultSubscription("test-subscription",
            Conditions.intrinsic(Intrinsic.TABLE, "review:testcustomer"),
            now, Duration.ofHours(48));

    SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    fmt.setTimeZone(TimeZone.getTimeZone("GMT"));

    ObjectMapper mapper = CustomJsonObjectMapperFactory.build();
    mapper.setDateFormat(fmt);

    String subscriptionString = mapper.writeValueAsString(expected);
    assertEquals(subscriptionString, "{" +
            "\"name\":\"test-subscription\"," +
            "\"tableFilter\":\"intrinsic(\\\"~table\\\":\\\"review:testcustomer\\\")\"," +
            "\"expiresAt\":\"" + nowString + "\"," +
            "\"eventTtl\":172800000" +
            "}");

    Subscription actual = JsonHelper.fromJson(subscriptionString, Subscription.class);
    assertEquals(actual.getName(), expected.getName());
    assertEquals(actual.getTableFilter(), expected.getTableFilter());
    assertEquals(actual.getExpiresAt(), expected.getExpiresAt());
    assertEquals(actual.getEventTtl(), expected.getEventTtl());
}
 
Example 11
Source File: WebMvcConfig.java    From EasyReport with Apache License 2.0 5 votes vote down vote up
@Bean
public CustomMappingJackson2HttpMessageConverter messageConverter() {
    final CustomMappingJackson2HttpMessageConverter converter = new CustomMappingJackson2HttpMessageConverter();
    final ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
    converter.setObjectMapper(objectMapper);
    return converter;
}
 
Example 12
Source File: JobsConfiguration.java    From zuihou-admin-boot with Apache License 2.0 5 votes vote down vote up
/**
 * json 类型参数 序列化问题
 * Long -> string
 * date -> string
 *
 * @param builder
 * @return
 */
@Bean
@Primary
@ConditionalOnMissingBean
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
    ObjectMapper objectMapper = builder.createXmlMapper(false)
            .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
            .timeZone(TimeZone.getTimeZone("Asia/Shanghai"))
            .build();
    //忽略未知字段
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    //日期格式
    SimpleDateFormat outputFormat = new SimpleDateFormat(DEFAULT_DATE_TIME_FORMAT);
    objectMapper.setDateFormat(outputFormat);
    SimpleModule simpleModule = new SimpleModule();
    /**
     *  将Long,BigInteger序列化的时候,转化为String
     */
    simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
    simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
    simpleModule.addSerializer(BigInteger.class, ToStringSerializer.instance);
    simpleModule.addSerializer(BigDecimal.class, ToStringSerializer.instance);

    objectMapper.registerModule(simpleModule);

    return objectMapper;
}
 
Example 13
Source File: JacksonDateUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenSettingObjectMapperDateFormat_thenCorrect() throws JsonProcessingException, ParseException {
    final SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm");

    final String toParse = "20-12-2014 02:30";
    final Date date = df.parse(toParse);
    final Event event = new Event("party", date);

    final ObjectMapper mapper = new ObjectMapper();
    mapper.setDateFormat(df);

    final String result = mapper.writeValueAsString(event);
    assertThat(result, containsString(toParse));
}
 
Example 14
Source File: AbstractMongoProcessor.java    From nifi with Apache License 2.0 5 votes vote down vote up
protected synchronized void configureMapper(String setting, String dateFormat) {
    objectMapper = new ObjectMapper();

    if (setting.equals(JSON_TYPE_STANDARD)) {
        objectMapper.registerModule(ObjectIdSerializer.getModule());
        DateFormat df = new SimpleDateFormat(dateFormat);
        objectMapper.setDateFormat(df);
    }
}
 
Example 15
Source File: BDSMicroRaidenApi.java    From asf-sdk with GNU General Public License v3.0 5 votes vote down vote up
static Converter.Factory createDefaultConverter() {
  ObjectMapper objectMapper = new ObjectMapper();

  DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
  objectMapper.setDateFormat(df);

  return JacksonConverterFactory.create(objectMapper);
}
 
Example 16
Source File: JsonConfig.java    From pmq with Apache License 2.0 5 votes vote down vote up
@Bean
@Primary
// @ConditionalOnMissingBean(ObjectMapper.class)
public ObjectMapper jacksonObjectMapper() {
	ObjectMapper objectMapper = new ObjectMapper();
	objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
	objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS"));
	// objectMapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
	objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
	objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
	return objectMapper;
}
 
Example 17
Source File: ExternalTaskClientBuilderImpl.java    From camunda-external-task-client-java with Apache License 2.0 5 votes vote down vote up
protected void initObjectMapper() {
  objectMapper = new ObjectMapper();
  objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
  objectMapper.configure(DeserializationFeature.FAIL_ON_UNRESOLVED_OBJECT_IDS, false);
  objectMapper.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, false);

  SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
  objectMapper.setDateFormat(sdf);
  objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
}
 
Example 18
Source File: OpenLRW.java    From OpenLRW with Educational Community License v2.0 5 votes vote down vote up
@Bean
public ObjectMapper objectMapper() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.findAndRegisterModules();
    mapper.setDateFormat(new ISO8601DateFormat());
    mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    return mapper;
}
 
Example 19
Source File: LoginFailureHandlerConfig.java    From base-admin with MIT License 4 votes vote down vote up
@Override
public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException {
    String msg = "{\"code\":\"400\",\"msg\":\"用户名或密码错误\"}";

    //判断api加密开关是否开启
    if("Y".equals(SysSettingUtil.getSysSetting().getSysApiEncrypt())){
        //加密
        try {
            //前端公钥
            String publicKey = httpServletRequest.getParameter("publicKey");

            log.info("前端公钥:" + publicKey);

            //jackson
            ObjectMapper mapper = new ObjectMapper();
            //jackson 序列化和反序列化 date处理
            mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            //每次响应之前随机获取AES的key,加密data数据
            String key = AesUtil.getKey();
            log.info("AES的key:" + key);
            log.info("需要加密的data数据:" + msg);
            String data = AesUtil.encrypt(msg, key);

            //用前端的公钥来解密AES的key,并转成Base64
            String aesKey = Base64.encodeBase64String(RsaUtil.encryptByPublicKey(key.getBytes(), publicKey));
            msg = "{\"data\":{\"data\":\"" + data + "\",\"aesKey\":\"" + aesKey + "\"}}";
        } catch (Throwable ee) {
            //输出到日志文件中
            log.error(ErrorUtil.errorInfoToString(ee));
        }
    }

    //转json字符串并转成Object对象,设置到Result中并赋值给返回值o
    httpServletResponse.setCharacterEncoding("UTF-8");
    httpServletResponse.setContentType("application/json; charset=utf-8");
    PrintWriter out = httpServletResponse.getWriter();
    out.print(msg);
    out.flush();
    out.close();
}
 
Example 20
Source File: JdbcJobRepositoryTests.java    From piper with Apache License 2.0 4 votes vote down vote up
private ObjectMapper createObjectMapper() {
  ObjectMapper objectMapper = new ObjectMapper();
  objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
  objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZ"));
  return objectMapper;
}