private static void setupMapper(ObjectMapper mapper) { // Serialize dates using ISO8601 format // Jackson uses timestamps by default, so use StdDateFormat to get ISO8601 mapper.getSerializationConfig().with(new StdDateFormat()); // Deserialize dates using ISO8601 format mapper.getDeserializationConfig().with(new StdDateFormat()); // Prevent exceptions from being thrown for unknown properties // mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, // false); mapper.addHandler(new DeserializationProblemHandler() { @Override public boolean handleUnknownProperty(DeserializationContext ctxt, JsonParser jp, JsonDeserializer<?> deserializer, Object beanOrClass, String propertyName) throws IOException, JsonProcessingException { return true; } }); // ignore fields with null values mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); }
/** * Constructor */ public Shogun2JsonObjectMapper() { super(); // register the joda module to support the joda time types, which are // used in shogun this.registerModule(new JodaModule()); // register JTS geometry types this.registerModule(new JtsModule()); // StdDateFormat is ISO8601 since jackson 2.9 configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); setDateFormat(new StdDateFormat()); setTimeZone(TimeZone.getDefault()); }
/** * {@inheritDoc} */ @Override public Date deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { JsonNode tree = jp.readValueAsTree(); if (tree.isPojo()) { POJONode pojoNode = (POJONode) tree; Object pojo = pojoNode.getPojo(); if (pojo instanceof Date) { return (Date) pojoNode.getPojo(); } else { throw new RuntimeException("unsupported date type, expected: " + Date.class.getName()); } } String stringDate = tree.asText(); StdDateFormat stdDateFormat = new StdDateFormat(); try { return stdDateFormat.parse(stringDate); } catch (ParseException e) { throw Throwables.propagate(e); } }
/** * Fluent factory for constructing a new instance that uses specified TimeZone. * Note that timezone used with also be assigned to configured {@link DateFormat}, * changing time formatting defaults. */ public BaseSettings with(TimeZone tz) { if (tz == null) { throw new IllegalArgumentException(); } DateFormat df = _dateFormat; if (df instanceof StdDateFormat) { df = ((StdDateFormat) df).withTimeZone(tz); } else { // we don't know if original format might be shared; better create a clone: df = (DateFormat) df.clone(); df.setTimeZone(tz); } return new BaseSettings(_classIntrospector, _annotationIntrospector, _visibilityChecker, _propertyNamingStrategy, _typeFactory, _typeResolverBuilder, df, _handlerInstantiator, _locale, tz, _defaultBase64); }
public ApacheHttpTransport(HttpClient httpClient, Crypto crypto, ObjectMapper objectMapper, Cache publicKeyCache, String baseUrl, EntityIdentifier issuer, JWTService jwtService, JWEService jweService, int offsetTTL, int currentPublicKeyTTL, EntityKeyMap entityKeyMap ) { this.objectMapper = objectMapper; this.objectMapper.setDateFormat(new StdDateFormat()); this.crypto = crypto; this.httpClient = httpClient; this.jwtService = jwtService; this.jweService = jweService; this.publicKeyCache = publicKeyCache; this.entityKeyMap = entityKeyMap; this.offsetTTL = offsetTTL; this.currentPublicKeyTTL = currentPublicKeyTTL; this.issuer = issuer; logger = LogFactory.getLog(getClass()); rbf = new ApiRequestBuilderFactory(issuer.toString(), baseUrl, objectMapper, crypto, jwtService, jweService); }
private static long parseDateToMillisecs(String valueAsText) { try { return Long.parseLong(valueAsText); } catch (NumberFormatException nfe) { try { return new StdDateFormat().parse(valueAsText).getTime(); } catch (ParseException pe) { throw new IllegalArgumentException("Unable to parse this string as a date: " + valueAsText); } } }
@Test public void noCustomDateFormat() throws Exception { this.context.register(JacksonAutoConfiguration.class); this.context.refresh(); ObjectMapper mapper = this.context.getBean(ObjectMapper.class); assertThat(mapper.getDateFormat()).isInstanceOf(StdDateFormat.class); }
private WebServiceClient(WebServiceClient.Builder builder) { host = builder.host; port = builder.port; useHttps = builder.useHttps; locales = builder.locales; licenseKey = builder.licenseKey; userId = builder.userId; mapper = new ObjectMapper(); mapper.disable(MapperFeature.CAN_OVERRIDE_ACCESS_MODIFIERS); mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); mapper.setDateFormat(new StdDateFormat().withColonInTimeZone(true)); RequestConfig.Builder configBuilder = RequestConfig.custom() .setConnectTimeout(builder.connectTimeout) .setSocketTimeout(builder.readTimeout); if (builder.proxy != null && builder.proxy != Proxy.NO_PROXY) { InetSocketAddress address = (InetSocketAddress) builder.proxy.address(); HttpHost proxyHost = new HttpHost(address.getHostName(), address.getPort()); configBuilder.setProxy(proxyHost); } RequestConfig config = configBuilder.build(); httpClient = HttpClientBuilder.create() .setUserAgent(userAgent()) .setDefaultRequestConfig(config).build(); }
/** * @return JSON representation of this object. * @throws IOException if there is an error serializing the object to JSON. */ public final String toJson() throws IOException { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); mapper.disable(MapperFeature.CAN_OVERRIDE_ACCESS_MODIFIERS); mapper.setDateFormat(new StdDateFormat().withColonInTimeZone(true)); mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); return mapper.writeValueAsString(this); }
private long parseDateToMillisecs(String valueAsText) { try { return Long.parseLong(valueAsText); } catch (NumberFormatException nfe) { try { return new StdDateFormat().parse(valueAsText).getTime(); } catch (ParseException pe) { throw new IllegalArgumentException("Unable to parse this string as a date: " + valueAsText); } } }
@Test public void noCustomDateFormat() throws Exception { this.context.register(JacksonAutoConfiguration.class); this.context.refresh(); ObjectMapper mapper = this.context.getBean(ObjectMapper.class); assertThat(mapper.getDateFormat(), is(instanceOf(StdDateFormat.class))); }
private static ObjectMapper createObjectMapper() { ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new Jdk8Module()); mapper.registerModule(new JavaTimeModule()); mapper.registerModule(new AfterburnerModule()); mapper.setDateFormat(new StdDateFormat()); mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.configure(MapperFeature.USE_WRAPPER_NAME_AS_PROPERTY_NAME, true); mapper.setAnnotationIntrospector(new JSONAnnotationIntrospector()); return mapper; }
public final BaseSettings with(TimeZone paramTimeZone) { if (paramTimeZone == null) throw new IllegalArgumentException(); DateFormat localDateFormat1 = this._dateFormat; Object localObject; if ((localDateFormat1 instanceof StdDateFormat)) { localObject = ((StdDateFormat)localDateFormat1).withTimeZone(paramTimeZone); } else { DateFormat localDateFormat2 = (DateFormat)localDateFormat1.clone(); localObject = localDateFormat2; localDateFormat2.setTimeZone(paramTimeZone); } ClassIntrospector localClassIntrospector = this._classIntrospector; AnnotationIntrospector localAnnotationIntrospector = this._annotationIntrospector; VisibilityChecker localVisibilityChecker = this._visibilityChecker; PropertyNamingStrategy localPropertyNamingStrategy = this._propertyNamingStrategy; TypeFactory localTypeFactory = this._typeFactory; TypeResolverBuilder localTypeResolverBuilder = this._typeResolverBuilder; HandlerInstantiator localHandlerInstantiator = this._handlerInstantiator; Locale localLocale = this._locale; Base64Variant localBase64Variant = this._defaultBase64; return new BaseSettings(localClassIntrospector, localAnnotationIntrospector, localVisibilityChecker, localPropertyNamingStrategy, localTypeFactory, localTypeResolverBuilder, (DateFormat)localObject, localHandlerInstantiator, localLocale, paramTimeZone, localBase64Variant); }
/** * Tests whether the dateFormat is ISO8601 */ @Test public void testDateFormat() { SerializationConfig serializationConfig = objectMapper.getSerializationConfig(); DeserializationConfig deserializationConfig = objectMapper.getDeserializationConfig(); DateFormat serializationDateFormat = serializationConfig.getDateFormat(); DateFormat deserializationDateFormat = deserializationConfig.getDateFormat(); assertThat(serializationDateFormat, instanceOf(StdDateFormat.class)); assertThat(deserializationDateFormat, instanceOf(StdDateFormat.class)); }
StenoEncoder(final JsonFactory jsonFactory, final ObjectMapper objectMapper) { // Initialize object mapper; _objectMapper = objectMapper; _objectMapper.setAnnotationIntrospector(new StenoAnnotationIntrospector(_objectMapper)); final SimpleFilterProvider simpleFilterProvider = new SimpleFilterProvider(); simpleFilterProvider.addFilter(RedactionFilter.REDACTION_FILTER_ID, new RedactionFilter(!DEFAULT_REDACT_NULL)); // Initialize this here based on the above code, if it was initialized at the declaration site then things // could get out of sync _redactEnabled = true; _objectMapper.setFilterProvider(simpleFilterProvider); // Setup writing of Date/DateTime values _objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); _objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); _objectMapper.setDateFormat(new StdDateFormat()); // Simple module with customizations final SimpleModule module = new SimpleModule(); module.setSerializerModifier(new StenoBeanSerializerModifier(this)); _objectMapper.registerModule(module); // Throwable mix-in _objectMapper.setMixIns(Collections.singletonMap(Throwable.class, ThrowableMixIn.class)); // After burner to improve data-bind performance _objectMapper.registerModule(new AfterburnerModule()); // Serialization strategies _listsSerialziationStrategy = new ListsSerialziationStrategy(this, jsonFactory, _objectMapper); _objectAsJsonSerialziationStrategy = new ObjectAsJsonSerialziationStrategy(this, jsonFactory, _objectMapper); _objectSerialziationStrategy = new ObjectSerialziationStrategy(this, jsonFactory, _objectMapper); _mapOfJsonSerialziationStrategy = new MapOfJsonSerialziationStrategy(this, jsonFactory, _objectMapper); _mapSerialziationStrategy = new MapSerialziationStrategy(this, jsonFactory, _objectMapper); _arrayOfJsonSerialziationStrategy = new ArrayOfJsonSerialziationStrategy(this, jsonFactory, _objectMapper); _arraySerialziationStrategy = new ArraySerialziationStrategy(this, jsonFactory, _objectMapper); _standardSerializationStrategy = new StandardSerializationStrategy(this, jsonFactory, _objectMapper); }
@Test public void datesUnmarshal() throws Exception { Date expected = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX").parse("2017-11-03T20:50:43Z"); Date actual = new ObjectMapper().setDateFormat(new StdDateFormat()).readValue( "{\"api_time\": \"2017-11-03T20:50:43Z\"}", PublicV3PingGetResponse.class ).getApiTime(); assertEquals(expected, actual); }
public JsonSerializer<?> createContextual(SerializerProvider paramSerializerProvider, BeanProperty paramBeanProperty) { if (paramBeanProperty != null) { JsonFormat.Value localValue = paramSerializerProvider.getAnnotationIntrospector().findFormat(paramBeanProperty.getMember()); if (localValue != null) { if (localValue.getShape().isNumeric()) return withFormat(true, null); TimeZone localTimeZone = localValue.getTimeZone(); String str = localValue.getPattern(); if (str.length() > 0) { Locale localLocale1 = localValue.getLocale(); Locale localLocale2 = localLocale1; if (localLocale1 == null) localLocale2 = paramSerializerProvider.getLocale(); SimpleDateFormat localSimpleDateFormat = new SimpleDateFormat(str, localLocale2); if (localTimeZone == null) localTimeZone = paramSerializerProvider.getTimeZone(); localSimpleDateFormat.setTimeZone(localTimeZone); return withFormat(false, localSimpleDateFormat); } if (localTimeZone != null) { DateFormat localDateFormat1 = paramSerializerProvider.getConfig().getDateFormat(); Object localObject; if (localDateFormat1.getClass() == StdDateFormat.class) { localObject = StdDateFormat.getISO8601Format(localTimeZone); } else { DateFormat localDateFormat2 = (DateFormat)localDateFormat1.clone(); localObject = localDateFormat2; localDateFormat2.setTimeZone(localTimeZone); } return withFormat(false, (DateFormat)localObject); } } } return this; }
public JsonDeserializer<?> createContextual(DeserializationContext paramDeserializationContext, BeanProperty paramBeanProperty) { if (paramBeanProperty != null) { JsonFormat.Value localValue = paramDeserializationContext.getAnnotationIntrospector().findFormat(paramBeanProperty.getMember()); if (localValue != null) { TimeZone localTimeZone = localValue.getTimeZone(); String str = localValue.getPattern(); if (str.length() > 0) { Locale localLocale1 = localValue.getLocale(); Locale localLocale2 = localLocale1; if (localLocale1 == null) localLocale2 = paramDeserializationContext.getLocale(); SimpleDateFormat localSimpleDateFormat = new SimpleDateFormat(str, localLocale2); if (localTimeZone == null) localTimeZone = paramDeserializationContext.getTimeZone(); localSimpleDateFormat.setTimeZone(localTimeZone); return withDateFormat(localSimpleDateFormat, str); } if (localTimeZone != null) { DateFormat localDateFormat1 = paramDeserializationContext.getConfig().getDateFormat(); Object localObject; if (localDateFormat1.getClass() == StdDateFormat.class) { localObject = ((StdDateFormat)localDateFormat1).withTimeZone(localTimeZone); } else { DateFormat localDateFormat2 = (DateFormat)localDateFormat1.clone(); localObject = localDateFormat2; localDateFormat2.setTimeZone(localTimeZone); } return withDateFormat((DateFormat)localObject, str); } } } return this; }