com.fasterxml.jackson.datatype.jsr310.JavaTimeModule类的使用及代码示例

x33g5p2x  于2022-01-21 转载在 其他  
字(16.0k)|赞(0)|评价(0)|浏览(1388)

本文整理了Java中com.fasterxml.jackson.datatype.jsr310.JavaTimeModule类的一些代码示例,展示了JavaTimeModule类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。JavaTimeModule类的具体详情如下:
包路径:com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
类名称:JavaTimeModule

JavaTimeModule介绍

[英]Class that registers capability of serializing java.time objects with the Jackson core.

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

Note that as of 2.6, this module does NOT support auto-registration, because of existence of legacy version, JSR310Module. Legacy version has the same functionality, but slightly different default configuration: see com.fasterxml.jackson.datatype.jsr310.JSR310Module for details.

Most java.time types are serialized as numbers (integers or decimals as appropriate) if the com.fasterxml.jackson.databind.SerializationFeature#WRITE_DATES_AS_TIMESTAMPS feature is enabled, and otherwise are serialized in standard ISO-8601 string representation. ISO-8601 specifies formats for representing offset dates and times, zoned dates and times, local dates and times, periods, durations, zones, and more. All java.time types have built-in translation to and from ISO-8601 formats.

Granularity of timestamps is controlled through the companion features com.fasterxml.jackson.databind.SerializationFeature#WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS and com.fasterxml.jackson.databind.DeserializationFeature#READ_DATE_TIMESTAMPS_AS_NANOSECONDS. For serialization, timestamps are written as fractional numbers (decimals), where the number is seconds and the decimal is fractional seconds, if WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS is enabled (it is by default), with resolution as fine as nanoseconds depending on the underlying JDK implementation. If WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS is disabled, timestamps are written as a whole number of milliseconds. At deserialization time, decimal numbers are always read as fractional second timestamps with up-to-nanosecond resolution, since the meaning of the decimal is unambiguous. The more ambiguous integer types are read as fractional seconds without a decimal point if READ_DATE_TIMESTAMPS_AS_NANOSECONDS is enabled (it is by default), and otherwise they are read as milliseconds.

Some exceptions to this standard serialization/deserialization rule:

  • Period, which always results in an ISO-8601 format because Periods must be represented in years, months, and/or days.
  • Year, which only contains a year and cannot be represented with a timestamp.
  • YearMonth, which only contains a year and a month and cannot be represented with a timestamp.
  • MonthDay, which only contains a month and a day and cannot be represented with a timestamp.
  • ZoneId and ZoneOffset, which do not actually store dates and times but are supported with this module nonetheless.
  • LocalDate, LocalTime, LocalDateTime, and OffsetTime, which cannot portably be converted to timestamps and are instead represented as arrays when WRITE_DATES_AS_TIMESTAMPS is enabled.
    [中]类,该类注册序列化java的功能。具有Jackson核心的时间对象
ObjectMapper mapper = new ObjectMapper(); 
mapper.registerModule(new JavaTimeModule());

请注意,从2.6开始,此模块不支持自动注册,因为存在旧版本JSR310模块。旧版本具有相同的功能,但默认配置略有不同:请参阅com。fasterxml。杰克逊。数据类型。jsr310。详细信息请参见JSR310模块。
大多数是java。如果com为空,则时间类型序列化为数字(整数或小数,视情况而定)。fasterxml。杰克逊。数据绑定。SerializationFeature#WRITE _DATES _AS _TIMESTAMPS功能已启用,否则将以标准ISO-8601字符串表示形式序列化。ISO-8601指定了表示偏移日期和时间、分区日期和时间、本地日期和时间、期间、持续时间、分区等的格式。全是java。时间类型具有与ISO-8601格式之间的内置转换。
时间戳的粒度通过com的配套功能进行控制。fasterxml。杰克逊。数据绑定。SerializationFeature#以纳秒和com的形式写入日期和时间戳。fasterxml。杰克逊。数据绑定。反序列化功能#读取"日期"时间戳"为"纳秒"。对于序列化,如果启用了WRITE_DATE_timestamps_as_NANOSECONDS(默认情况下),则时间戳被写入小数(decimals),其中数字为秒,小数为小数秒,分辨率为纳秒,具体取决于底层JDK实现。如果禁用将时间戳写入为纳秒,则时间戳将以毫秒为整数写入。在反序列化时,十进制数总是以高达纳秒分辨率的分数秒时间戳读取,因为十进制数的含义是明确的。如果启用了read_DATE_TIMESTAMPS_as_NANOSECONDS(默认情况下),则更不明确的整数类型将被读取为不带小数点的小数秒,否则将被读取为毫秒。
此标准序列化/反序列化规则的某些例外情况:
*期间,它总是以ISO-8601格式显示,因为期间必须以年、月和/或天表示。
*年,它只包含一年,不能用时间戳表示。
*YearMonth,仅包含一年和一个月,不能用时间戳表示。
*MonthDay,它只包含一个月和一天,不能用时间戳表示。
*ZoneId和ZoneOffset,它们实际上不存储日期和时间,但此模块仍支持它们。
*LocalDate、LocalTime、LocalDateTime和OffsetTime,它们不能可移植地转换为时间戳,而是在启用WRITE_DATES_as_时间戳时表示为数组。

代码示例

代码示例来源:origin: stackoverflow.com

@Service 
@Provider
public class ObjectMapperContextResolver implements ContextResolver<ObjectMapper> {  
  private final ObjectMapper mapper;

  public ObjectMapperContextResolver() {
    mapper = new ObjectMapper();
    JavaTimeModule javaTimeModule=new JavaTimeModule();
    // Hack time module to allow 'Z' at the end of string (i.e. javascript json's) 
    javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ISO_DATE_TIME));
    mapper.registerModule(javaTimeModule);
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
  }

  @Override
  public ObjectMapper getContext(Class<?> type) {
    return mapper;
  }  
}

代码示例来源:origin: com.fasterxml.jackson.datatype/jackson-datatype-jsr310

addDeserializer(Instant.class, InstantDeserializer.INSTANT);
addDeserializer(OffsetDateTime.class, InstantDeserializer.OFFSET_DATE_TIME);
addDeserializer(ZonedDateTime.class, InstantDeserializer.ZONED_DATE_TIME);
addDeserializer(Duration.class, DurationDeserializer.INSTANCE);
addDeserializer(LocalDateTime.class, LocalDateTimeDeserializer.INSTANCE);
addDeserializer(LocalDate.class, LocalDateDeserializer.INSTANCE);
addDeserializer(LocalTime.class, LocalTimeDeserializer.INSTANCE);
addDeserializer(MonthDay.class, MonthDayDeserializer.INSTANCE);
addDeserializer(OffsetTime.class, OffsetTimeDeserializer.INSTANCE);
addDeserializer(Period.class, JSR310StringParsableDeserializer.PERIOD);
addDeserializer(Year.class, YearDeserializer.INSTANCE);
addDeserializer(YearMonth.class, YearMonthDeserializer.INSTANCE);
addDeserializer(ZoneId.class, JSR310StringParsableDeserializer.ZONE_ID);
addDeserializer(ZoneOffset.class, JSR310StringParsableDeserializer.ZONE_OFFSET);
addSerializer(Duration.class, DurationSerializer.INSTANCE);
addSerializer(Instant.class, InstantSerializer.INSTANCE);
addSerializer(LocalDateTime.class, LocalDateTimeSerializer.INSTANCE);
addSerializer(LocalDate.class, LocalDateSerializer.INSTANCE);
addSerializer(LocalTime.class, LocalTimeSerializer.INSTANCE);
addSerializer(MonthDay.class, MonthDaySerializer.INSTANCE);
addSerializer(OffsetDateTime.class, OffsetDateTimeSerializer.INSTANCE);
addSerializer(OffsetTime.class, OffsetTimeSerializer.INSTANCE);
addSerializer(Period.class, new ToStringSerializer(Period.class));
addSerializer(Year.class, YearSerializer.INSTANCE);
addSerializer(YearMonth.class, YearMonthSerializer.INSTANCE);
addSerializer(ZonedDateTime.class, ZonedDateTimeSerializer.INSTANCE);

代码示例来源:origin: google/data-transfer-project

public static ObjectMapper createObjectMapper() {
  ObjectMapper objectMapper = new ObjectMapper();
  objectMapper.registerModule(new JavaTimeModule());
  return objectMapper;
 }
}

代码示例来源:origin: uber/AthenaX

public ApiClient() {
 objectMapper = new ObjectMapper();
 objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
 objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
 objectMapper.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, false);
 objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
 objectMapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
 objectMapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
 objectMapper.registerModule(new JavaTimeModule());
 objectMapper.setDateFormat(ApiClient.buildDefaultDateFormat());
 dateFormat = ApiClient.buildDefaultDateFormat();
 // Set default User-Agent.
 setUserAgent("Swagger-Codegen/1.0.0/java");
 // Setup authentications (key: authentication name, value: authentication).
 authentications = new HashMap<String, Authentication>();
 // Prevent the authentications from being modified.
 authentications = Collections.unmodifiableMap(authentications);
 rebuildHttpClient();
}

代码示例来源:origin: google/data-transfer-project

@Test
 public void verifySerializeDeserialize() throws Exception {
  ObjectMapper objectMapper = new ObjectMapper();
  objectMapper.registerModule(new JavaTimeModule());
  objectMapper.registerSubtypes(TaskContainerResource.class);

  List<TaskListModel> taskLists = ImmutableList.of(new TaskListModel("id1", "List 1"));

  List<TaskModel> tasks =
    ImmutableList.of(
      new TaskModel("id1", "Write Better tests", "Do this soon", null, null),
      new TaskModel("id1", "Liberate all the data", "do this in stages", null, null));

  ContainerResource data = new TaskContainerResource(taskLists, tasks);

  String serialized = objectMapper.writeValueAsString(data);

  ContainerResource deserializedModel =
    objectMapper.readValue(serialized, ContainerResource.class);

  Truth.assertThat(deserializedModel).isNotNull();
  Truth.assertThat(deserializedModel).isInstanceOf(TaskContainerResource.class);
  TaskContainerResource deserialized = (TaskContainerResource) deserializedModel;
  Truth.assertThat(deserialized.getLists()).hasSize(1);
  Truth.assertThat(deserialized.getTasks()).hasSize(2);
 }
}

代码示例来源:origin: de.digitalcollections.workflow/dc-workflow-engine

public RabbitClient(MessageBrokerConfig config, RabbitConnection connection) {
 this.connection = connection;
 channel = connection.getChannel();
 objectMapper = new ObjectMapper();
 messageClass = config.getMessageClass();
 objectMapper.registerModules(config.getJacksonModules());
 objectMapper.addMixIn(Envelope.class, EnvelopeMixin.class);
 objectMapper.registerModule(new JavaTimeModule());
 if (objectMapper.findMixInClassFor(Message.class) == null) {
  objectMapper.addMixIn(DefaultMessage.class, DefaultMessageMixin.class);
 }
}

代码示例来源:origin: Graylog2/graylog2-server

@Inject
public ObjectMapperProvider(@GraylogClassLoader final ClassLoader classLoader,
              @JacksonSubTypes Set<NamedType> subtypes) {
  final ObjectMapper mapper = new ObjectMapper();
  final TypeFactory typeFactory = mapper.getTypeFactory().withClassLoader(classLoader);
  final AutoValueSubtypeResolver subtypeResolver = new AutoValueSubtypeResolver();
      .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
      .disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE)
      .disable(DeserializationFeature.FAIL_ON_MISSING_EXTERNAL_TYPE_ID_PROPERTY)
      .registerModule(new JodaModule())
      .registerModule(new Jdk8Module())
      .registerModule(new JavaTimeModule())
      .registerModule(new MetricsModule(TimeUnit.SECONDS, TimeUnit.SECONDS, false))
      .registerModule(new SimpleModule("Graylog")

代码示例来源:origin: com.mercateo.eventstore/client-common

public EventJsonMapper() {
  objectMapper = new ObjectMapper();
  objectMapper.registerModules(new Jdk8Module(), new JavaTimeModule());
  objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
  objectMapper.registerModule(new VavrModule());
  objectMapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
}

代码示例来源:origin: jooby-project/jooby

ObjectMapper m = new ObjectMapper();
Locale locale = env.locale();
m.setDateFormat(new SimpleDateFormat(config.getString("application.dateFormat"), locale));
m.setLocale(locale);
m.setTimeZone(TimeZone.getTimeZone(config.getString("application.tz")));
m.registerModule(new Jdk8Module());
m.registerModule(new JavaTimeModule());
m.registerModule(new ParameterNamesModule());
m.registerModule(new AfterburnerModule());

代码示例来源:origin: spotify/spydra

public static ObjectMapper objectMapper() {
  return new ObjectMapper()
    .setPropertyNamingStrategy(SNAKE_CASE)
    .enable(ACCEPT_SINGLE_VALUE_AS_ARRAY)
    .registerModule(new JavaTimeModule())
    .registerModule(new Jdk8Module())
    .registerModule(new ParameterNamesModule())
    .setSerializationInclusion(JsonInclude.Include.NON_NULL);
 }
}

代码示例来源:origin: spinnaker/kayenta

static public void configureObjectMapperFeatures(ObjectMapper objectMapper) {
 objectMapper.setSerializationInclusion(NON_NULL)
  .disable(FAIL_ON_UNKNOWN_PROPERTIES)
  .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
 JavaTimeModule module = new JavaTimeModule();
 objectMapper.registerModule(module);
}

代码示例来源:origin: SpectoLabs/hoverfly-java

@Before
public void setUp() throws Exception {
  objectMapper.registerModule(new JavaTimeModule());
  Journal journal = objectMapper.readValue(resource, Journal.class);
  journalEntry = journal.getEntries().iterator().next();
}

代码示例来源:origin: blox/blox

public static ObjectMapper configureMapper(ObjectMapper mapper) {
  return mapper
    .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false)
    .registerModule(new JavaTimeModule());
 }
}

代码示例来源:origin: stackoverflow.com

@RunWith(JUnit4.class)
public class InstantNoMillisTest {

  private ObjectMapper objectMapper;

  @Before
  public void init() {
    JavaTimeModule module = new JavaTimeModule();
    ZonedDateTimeSerializer zonedDateTimeSerializer = new ZonedDateTimeSerializer(new DateTimeFormatterBuilder().appendInstant(0).toFormatter());
    module.addSerializer(ZonedDateTime.class, zonedDateTimeSerializer);
    objectMapper = Jackson2ObjectMapperBuilder.json()
        .modules(module)
        .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
        .build();
  }

  @Test
  public void test() throws IOException {
    ZonedDateTime zonedDateTime = ZonedDateTime.now();
    String noMillis = objectMapper.writeValueAsString(zonedDateTime);
    System.out.print(noMillis);
  }
}

代码示例来源:origin: org.springframework.cloud/spring-cloud-dataflow-server-core

private void setupObjectMapper(ObjectMapper objectMapper) {
  objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
  objectMapper.setDateFormat(new ISO8601DateFormatWithMilliSeconds());
  objectMapper.addMixIn(StepExecution.class, StepExecutionJacksonMixIn.class);
  objectMapper.addMixIn(ExecutionContext.class, ExecutionContextJacksonMixIn.class);
  objectMapper.registerModule(new JavaTimeModule());
}

代码示例来源:origin: dropwizard/dropwizard

private static ObjectMapper configure(ObjectMapper mapper) {
    mapper.registerModule(new GuavaModule());
    mapper.registerModule(new GuavaExtrasModule());
    mapper.registerModule(new CaffeineModule());
    mapper.registerModule(new JodaModule());
    mapper.registerModule(new AfterburnerModule());
    mapper.registerModule(new FuzzyEnumModule());
    mapper.registerModule(new ParameterNamesModule());
    mapper.registerModule(new Jdk8Module());
    mapper.registerModule(new JavaTimeModule());
    mapper.setPropertyNamingStrategy(new AnnotationSensitivePropertyNamingStrategy());
    mapper.setSubtypeResolver(new DiscoverableSubtypeResolver());
    mapper.disable(FAIL_ON_UNKNOWN_PROPERTIES);

    return mapper;
  }
}

代码示例来源:origin: stackoverflow.com

@Configuration
class RepositoryRestAdapterConfiguration extends RepositoryRestConfigurerAdapter {

  @Override
  public void configureJacksonObjectMapper(ObjectMapper objectMapper) {
    objectMapper.registerModule(new JavaTimeModule());
    objectMapper.disable( SerializationFeature.WRITE_DATES_AS_TIMESTAMPS );
  }

}

代码示例来源:origin: AxonFramework/AxonFramework

/**
 * Instantiate a {@link JacksonSerializer} based on the fields contained in the {@link Builder}.
 * <p>
 * Upon instantiation, the ObjectMapper will get two modules registered to it by default, (1) the
 * {@link MetaDataDeserializer} and the (2) {@link JavaTimeModule}. Lastly, if the provided converter is of type
 * ChainingConverter, the {@link JacksonSerializer#registerConverters} is performed to automatically add the
 * {@link JsonNodeToByteArrayConverter} and {@link ByteArrayToJsonNodeConverter}.
 *
 * @param builder the {@link Builder} used to instantiate a {@link JacksonSerializer} instance
 */
protected JacksonSerializer(Builder builder) {
  builder.validate();
  this.revisionResolver = builder.revisionResolver;
  this.converter = builder.converter;
  this.objectMapper = builder.objectMapper;
  this.classLoader = builder.classLoader;
  this.objectMapper.registerModule(
      new SimpleModule("Axon-Jackson Module").addDeserializer(MetaData.class, new MetaDataDeserializer())
  );
  this.objectMapper.registerModule(new JavaTimeModule());
  if (converter instanceof ChainingConverter) {
    registerConverters((ChainingConverter) converter);
  }
}

代码示例来源:origin: stackoverflow.com

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

ObjectMapper mapper = Jackson2ObjectMapperBuilder
      .json()       
      .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) 
      .modules(new JavaTimeModule())
      .dateFormat(dateFormat)
      .build();

代码示例来源:origin: stackoverflow.com

@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);
 }

相关文章

微信公众号

最新文章

更多