如何使用 Jackson JSON 处理器序列化 Joda DateTime?

发布于 2024-09-10 13:57:47 字数 328 浏览 14 评论 0原文

如何让 Jackson 根据简单的模式(如“dd-MM-yyyy”)序列化我的 Joda DateTime 对象?

我试过了:

@JsonSerialize(using=DateTimeSerializer.class)
private final DateTime date;

我也试过了:

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

谢谢!

How do I get Jackson to serialize my Joda DateTime object according to a simple pattern (like "dd-MM-yyyy")?

I've tried:

@JsonSerialize(using=DateTimeSerializer.class)
private final DateTime date;

I've also tried:

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

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

廻憶裏菂餘溫 2024-09-17 13:57:47

使用 Jackson 2.0 和 Joda 模块,这变得非常容易。

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

Maven依赖:

<dependency>
  <groupId>com.fasterxml.jackson.datatype</groupId>
  <artifactId>jackson-datatype-joda</artifactId>
  <version>2.1.1</version>
</dependency>  

代码和文档:
https://github.com/FasterXML/jackson-datatype-joda

二进制文件:
http://repo1.maven.org/maven2/com/fasterxml/jackson /数据类型/杰克逊-数据类型-joda/

This has become very easy with Jackson 2.0 and the Joda module.

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

Maven dependency:

<dependency>
  <groupId>com.fasterxml.jackson.datatype</groupId>
  <artifactId>jackson-datatype-joda</artifactId>
  <version>2.1.1</version>
</dependency>  

Code and documentation:
https://github.com/FasterXML/jackson-datatype-joda

Binaries:
http://repo1.maven.org/maven2/com/fasterxml/jackson/datatype/jackson-datatype-joda/

风吹过旳痕迹 2024-09-17 13:57:47

在您要映射的对象中:

@JsonSerialize(using = CustomDateSerializer.class)
public DateTime getDate() { ... }

在 CustomDateSerializer 中:

public class CustomDateSerializer extends JsonSerializer<DateTime> {

    private static DateTimeFormatter formatter = 
        DateTimeFormat.forPattern("dd-MM-yyyy");

    @Override
    public void serialize(DateTime value, JsonGenerator gen, 
                          SerializerProvider arg2)
        throws IOException, JsonProcessingException {

        gen.writeString(formatter.print(value));
    }
}

In the object you're mapping:

@JsonSerialize(using = CustomDateSerializer.class)
public DateTime getDate() { ... }

In CustomDateSerializer:

public class CustomDateSerializer extends JsonSerializer<DateTime> {

    private static DateTimeFormatter formatter = 
        DateTimeFormat.forPattern("dd-MM-yyyy");

    @Override
    public void serialize(DateTime value, JsonGenerator gen, 
                          SerializerProvider arg2)
        throws IOException, JsonProcessingException {

        gen.writeString(formatter.print(value));
    }
}
栖竹 2024-09-17 13:57:47

正如 @Kimble 所说,对于 Jackson 2,使用默认格式非常简单;只需在您的 ObjectMapper 上注册 JodaModule 即可。

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

对于DateTime的自定义序列化/反序列化,您需要实现自己的StdScalarSerializerStdScalarDeserializer;这很复杂,但无论如何。

例如,这是一个使用 ISODateFormat 和 UTC 时区的 DateTime 序列化器:

public class DateTimeSerializer extends StdScalarSerializer<DateTime> {

    public DateTimeSerializer() {
        super(DateTime.class);
    }

    @Override
    public void serialize(DateTime dateTime,
                          JsonGenerator jsonGenerator,
                          SerializerProvider provider) throws IOException, JsonGenerationException {
        String dateTimeAsString = ISODateTimeFormat.withZoneUTC().print(dateTime);
        jsonGenerator.writeString(dateTimeAsString);
    }
}

以及相应的反序列化器:

public class DateTimeDesrializer extends StdScalarDeserializer<DateTime> {

    public DateTimeDesrializer() {
        super(DateTime.class);
    }

    @Override
    public DateTime deserialize(JsonParser jsonParser,
                                DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        try {
            JsonToken currentToken = jsonParser.getCurrentToken();
            if (currentToken == JsonToken.VALUE_STRING) {
                String dateTimeAsString = jsonParser.getText().trim();
                return ISODateTimeFormat.withZoneUTC().parseDateTime(dateTimeAsString);
            }
        } finally {
            throw deserializationContext.mappingException(getValueClass());
        }
    }

然后将它们与模块绑定在一起:

public class DateTimeModule extends SimpleModule {

    public DateTimeModule() {
        super();
        addSerializer(DateTime.class, new DateTimeSerializer());
        addDeserializer(DateTime.class, new DateTimeDeserializer());
    }
}

然后注册模块在您的ObjectMapper上:

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

As @Kimble has said, with Jackson 2, using the default formatting is very easy; simply register JodaModule on your ObjectMapper.

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

For custom serialization/de-serialization of DateTime, you need to implement your own StdScalarSerializer and StdScalarDeserializer; it's pretty convoluted, but anyway.

For example, here's a DateTime serializer that uses the ISODateFormat with the UTC time zone:

public class DateTimeSerializer extends StdScalarSerializer<DateTime> {

    public DateTimeSerializer() {
        super(DateTime.class);
    }

    @Override
    public void serialize(DateTime dateTime,
                          JsonGenerator jsonGenerator,
                          SerializerProvider provider) throws IOException, JsonGenerationException {
        String dateTimeAsString = ISODateTimeFormat.withZoneUTC().print(dateTime);
        jsonGenerator.writeString(dateTimeAsString);
    }
}

And the corresponding de-serializer:

public class DateTimeDesrializer extends StdScalarDeserializer<DateTime> {

    public DateTimeDesrializer() {
        super(DateTime.class);
    }

    @Override
    public DateTime deserialize(JsonParser jsonParser,
                                DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        try {
            JsonToken currentToken = jsonParser.getCurrentToken();
            if (currentToken == JsonToken.VALUE_STRING) {
                String dateTimeAsString = jsonParser.getText().trim();
                return ISODateTimeFormat.withZoneUTC().parseDateTime(dateTimeAsString);
            }
        } finally {
            throw deserializationContext.mappingException(getValueClass());
        }
    }

Then tie these together with a module:

public class DateTimeModule extends SimpleModule {

    public DateTimeModule() {
        super();
        addSerializer(DateTime.class, new DateTimeSerializer());
        addDeserializer(DateTime.class, new DateTimeDeserializer());
    }
}

Then register the module on your ObjectMapper:

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new DateTimeModule());
吻安 2024-09-17 13:57:47

简单的解决方案

我遇到过类似的问题,我的解决方案比上面清楚得多。

我只是使用了 @JsonFormat 注释中的模式

基本上我的类有一个 DateTime 字段,所以我添加了一个注释围绕 getter:

@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
public DateTime getDate() {
    return date;
}

我使用 ObjectMapper 序列化该类,

    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new JodaModule());
    mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    ObjectWriter ow = mapper.writer();
    try {
        String logStr = ow.writeValueAsString(log);
        outLogger.info(logStr);
    } catch (IOException e) {
        logger.warn("JSON mapping exception", e);
    }

我们使用 Jackson 2.5.4

The easy solution

I have encountered similar problem and my solution is much clear than above.

I simply used the pattern in @JsonFormat annotation

Basically my class has a DateTime field, so I put an annotation around the getter:

@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
public DateTime getDate() {
    return date;
}

I serialize the class with ObjectMapper

    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new JodaModule());
    mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    ObjectWriter ow = mapper.writer();
    try {
        String logStr = ow.writeValueAsString(log);
        outLogger.info(logStr);
    } catch (IOException e) {
        logger.warn("JSON mapping exception", e);
    }

We use Jackson 2.5.4

隔纱相望 2024-09-17 13:57:47

https://stackoverflow.com/a/10835114/1113510

虽然您可以为每个日期字段添加注释,但更好为您的对象映射器进行全局配置。如果您使用 jackson,您可以按如下方式配置 spring:

<bean id="jacksonObjectMapper" class="com.company.CustomObjectMapper" />

<bean id="jacksonSerializationConfig" class="org.codehaus.jackson.map.SerializationConfig"
    factory-bean="jacksonObjectMapper" factory-method="getSerializationConfig" >
</bean>

对于 CustomObjectMapper:

public class CustomObjectMapper extends ObjectMapper {

    public CustomObjectMapper() {
        super();
        configure(Feature.WRITE_DATES_AS_TIMESTAMPS, false);
        setDateFormat(new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss 'GMT'ZZZ (z)"));
    }
}

当然,SimpleDateFormat 可以使用您需要的任何格式。

https://stackoverflow.com/a/10835114/1113510

Although you can put an annotation for each date field, is better to do a global configuration for your object mapper. If you use jackson you can configure your spring as follow:

<bean id="jacksonObjectMapper" class="com.company.CustomObjectMapper" />

<bean id="jacksonSerializationConfig" class="org.codehaus.jackson.map.SerializationConfig"
    factory-bean="jacksonObjectMapper" factory-method="getSerializationConfig" >
</bean>

For CustomObjectMapper:

public class CustomObjectMapper extends ObjectMapper {

    public CustomObjectMapper() {
        super();
        configure(Feature.WRITE_DATES_AS_TIMESTAMPS, false);
        setDateFormat(new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss 'GMT'ZZZ (z)"));
    }
}

Of course, SimpleDateFormat can use any format you need.

爱的故事 2024-09-17 13:57:47

同时,当 JodaModule 位于类路径中时,Jackson 会自动注册 Joda 模块。我刚刚将 jackson-datatype-joda 添加到 Maven,它立即生效。

<dependency>
  <groupId>com.fasterxml.jackson.datatype</groupId>
  <artifactId>jackson-datatype-joda</artifactId>
  <version>2.8.7</version>
</dependency>

JSON 输出:

{"created" : "2017-03-28T05:59:27.258Z"}

Meanwhile Jackson registers the Joda module automatically when the JodaModule is in classpath. I just added jackson-datatype-joda to Maven and it worked instantly.

<dependency>
  <groupId>com.fasterxml.jackson.datatype</groupId>
  <artifactId>jackson-datatype-joda</artifactId>
  <version>2.8.7</version>
</dependency>

JSON output:

{"created" : "2017-03-28T05:59:27.258Z"}
執念 2024-09-17 13:57:47

对于使用 Spring Boot 的用户,您必须将模块添加到您的上下文中,它将像这样添加到您的配置中。

@Bean
public Module jodaTimeModule() {
    return new JodaModule();
}

如果你想使用新的java8时间模块jsr-310。

@Bean
public Module jodaTimeModule() {
    return new JavaTimeModule();
}

For those with Spring Boot you have to add the module to your context and it will be added to your configuration like this.

@Bean
public Module jodaTimeModule() {
    return new JodaModule();
}

And if you want to use the new java8 time module jsr-310.

@Bean
public Module jodaTimeModule() {
    return new JavaTimeModule();
}
半透明的墙 2024-09-17 13:57:47

我正在使用 Java 8,这对我有用。

添加对 pom.xml 的依赖

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
    <version>2.4.0</version>
</dependency>

,并在 ObjectMapper 上添加 JodaModule

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

I'm using Java 8 and this worked for me.

Add the dependency on pom.xml

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
    <version>2.4.0</version>
</dependency>

and add JodaModule on your ObjectMapper

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JodaModule());
一影成城 2024-09-17 13:57:47

似乎对于 Jackson 1.9.12 默认情况下不存在这种可能性,因为:

public final static class DateTimeSerializer
    extends JodaSerializer<DateTime>
{
    public DateTimeSerializer() { super(DateTime.class); }

    @Override
    public void serialize(DateTime value, JsonGenerator jgen, SerializerProvider provider)
        throws IOException, JsonGenerationException
    {
        if (provider.isEnabled(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS)) {
            jgen.writeNumber(value.getMillis());
        } else {
            jgen.writeString(value.toString());
        }
    }

    @Override
    public JsonNode getSchema(SerializerProvider provider, java.lang.reflect.Type typeHint)
    {
        return createSchemaNode(provider.isEnabled(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS)
                ? "number" : "string", true);
    }
}

该类使用 Joda DateTime 的 toString() 方法序列化数据。

Rusty Kuntz 提出的方法非常适合我的案例。

It seems that for Jackson 1.9.12 there is no such possibility by default, because of:

public final static class DateTimeSerializer
    extends JodaSerializer<DateTime>
{
    public DateTimeSerializer() { super(DateTime.class); }

    @Override
    public void serialize(DateTime value, JsonGenerator jgen, SerializerProvider provider)
        throws IOException, JsonGenerationException
    {
        if (provider.isEnabled(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS)) {
            jgen.writeNumber(value.getMillis());
        } else {
            jgen.writeString(value.toString());
        }
    }

    @Override
    public JsonNode getSchema(SerializerProvider provider, java.lang.reflect.Type typeHint)
    {
        return createSchemaNode(provider.isEnabled(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS)
                ? "number" : "string", true);
    }
}

This class serializes data using toString() method of Joda DateTime.

Approach proposed by Rusty Kuntz works perfect for my case.

尘世孤行 2024-09-17 13:57:47

使用内置 Joda 序列化器/反序列化器进行轻松配置

如果您想要自定义格式,则无需编写自定义序列化器或反序列化器。 jackson-datatype-joda 2.x 提供了 DateTimeSerializerDateTimeDeserializer 您可以在其上设置 DateTimeFormatter > 使用,为您提供自定义格式。然后,在添加模块时将配置的序列化器和/或反序列化器添加到 JodaModule 中。

使用提供的序列化器/反序列化器(相对于自定义序列化器)的一个优点是,您可以使用 @JsonFormat(pattern = ". . .") 注释任何 DateTime 属性以覆盖您配置的格式。大多数其他答案(从 Jackson 1.x 开始)中显示的自定义序列化器/反序列化器将不支持 @JsonFormat 注释。因此,如果您有一个奇怪的 DateTime 值需要不同的格式,那么很容易处理,如下面的示例所示。

除了DateTimeSerializerDateTimeDeserializer之外,还有LocalDateSerializer/LocalDateDeserializerPeriodSerializer< /code>/PeriodDeserializer 等。

示例

下面是一个 Java 和一个 Kotlin 示例。您需要将以下内容添加到依赖项中:

com.fasterxml.jackson.datatype:jackson-datatype-joda:{version}

这些示例显示了设置默认自定义格式以及在通过 @JsonFormat 注释基于每个属性。

Java 示例

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.fasterxml.jackson.datatype.joda.JodaModule;
import com.fasterxml.jackson.datatype.joda.cfg.JacksonJodaDateFormat;
import com.fasterxml.jackson.datatype.joda.deser.DateTimeDeserializer;
import com.fasterxml.jackson.datatype.joda.ser.DateTimeSerializer;
import org.joda.time.DateTime;
import org.joda.time.ReadableInstant;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;



public class JacksonJodaTimeJavaExample
{
    private static final DateTimeFormatter DATE_TIME_FORMATTER =
        DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZZ");
    private static final JacksonJodaDateFormat JACKSON_JODA_DATE_FORMAT =
        new JacksonJodaDateFormat(DATE_TIME_FORMATTER);

    private static ObjectMapper mapper = createMapper();

    private static ObjectMapper createMapper()
    {
        return JsonMapper
            .builder()
            .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
            .addModule(new JodaModule()
                           // If you do not want to customize the formatting, you can remove the next two lines
                           .addSerializer(new DateTimeSerializer(JACKSON_JODA_DATE_FORMAT))
                           .addDeserializer(ReadableInstant.class, new DateTimeDeserializer(ReadableInstant.class, JACKSON_JODA_DATE_FORMAT))
            )
            // Enable pretty printing for our example
            .enable(SerializationFeature.INDENT_OUTPUT)
            .build();
    }

    record Event(
        DateTime startTime,
        DateTime endTime,
        @JsonFormat(pattern = "yyyy-MM-dd 'at' HH:mm:ss")
        DateTime dateTimeInAlternateFormat
    ) {}


    public static void main(String[] args) throws Exception
    {
        final DateTime now = DateTime.now();
        Event event = new Event(now, now.plusHours(1), now);

        String json = mapper.writeValueAsString(event);
        System.out.println(json);

        Event deserializedEvent = mapper.readValue(json, Event.class);
        System.out.println(deserializedEvent);
    }
}

Kotlin 示例

import com.fasterxml.jackson.annotation.JsonFormat
import com.fasterxml.jackson.databind.SerializationFeature
import com.fasterxml.jackson.databind.json.JsonMapper
import com.fasterxml.jackson.datatype.joda.JodaModule
import com.fasterxml.jackson.datatype.joda.cfg.JacksonJodaDateFormat
import com.fasterxml.jackson.datatype.joda.deser.DateTimeDeserializer
import com.fasterxml.jackson.datatype.joda.ser.DateTimeSerializer
import org.joda.time.DateTime
import org.joda.time.ReadableInstant
import org.joda.time.format.DateTimeFormat

object JacksonJodaTimeKotlinExample
{
    private val DATE_TIME_FORMATTER = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZZ")
    private val JACKSON_JODA_DATE_FORMAT = JacksonJodaDateFormat(DATE_TIME_FORMATTER)
    private val mapper = createMapper()

    private fun createMapper() =
        JsonMapper
        .builder()
        .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
        .addModule(
            // If you do not want to customize the formatting, you can remove the "apply" block
            JodaModule().apply {
                addSerializer(DateTimeSerializer(JACKSON_JODA_DATE_FORMAT))
                addDeserializer(ReadableInstant::class.java, DateTimeDeserializer(ReadableInstant::class.java, JACKSON_JODA_DATE_FORMAT))
            })
        // Enable pretty printing for our example
        .enable(SerializationFeature.INDENT_OUTPUT)
        .build()

    data class Event(
        var startTime: DateTime? = null,
        var endTime: DateTime? = null,
        // If we want a DateTime in an alternate format, we can
        @JsonFormat(pattern = "yyyy-MM-dd 'at' HH:mm:ss")
        var dateTimeInAlternateFormat: DateTime? = null)

    fun runExample()
    {
        val now = DateTime.now()
        val event = Event(now, now.plusHours(1), now)
        val json = mapper.writeValueAsString(event)
        println(json)
        val deserializedEvent = mapper.readValue(json, Event::class.java)
        println(deserializedEvent)
    }
}

fun main()
{
    JacksonJodaTimeKotlinExample.runExample()
}

Use Built-in Joda Serializer/Deserializer for easy config

If you want custom formatting, there's no need to write a custom Serializer or Deserializer. jackson-datatype-joda 2.x provides a DateTimeSerializer and DateTimeDeserializer on which you can set a DateTimeFormatter to use, providing you custom formatting. You then add the configured Serializer and/or Deserializer to the JodaModule when you add the module.

An advantage of using the provided Serializer/Deserializer (over custom ones) is that you can annotated any DateTime properties with @JsonFormat(pattern = ". . .") to override the format you configure. The custom Serializers/Deserializers shown in most of the other answers (from the Jackson 1.x days) will not honor @JsonFormat annotations. So if you have that one odd ball DateTime value that needs a a different format, it is easily handled, as shown in the below examples.

In addition to the DateTimeSerializer and DateTimeDeserializer, there are others such as LocalDateSerializer/LocalDateDeserializer, PeriodSerializer/PeriodDeserializer, etc.

Examples

Below is a Java and a Kotlin example. You will need to add the following to your dependencies:

com.fasterxml.jackson.datatype:jackson-datatype-joda:{version}

The examples show setting a default custom format, and overriding that format on a per property basis via the @JsonFormat annotation.

Java Example

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.fasterxml.jackson.datatype.joda.JodaModule;
import com.fasterxml.jackson.datatype.joda.cfg.JacksonJodaDateFormat;
import com.fasterxml.jackson.datatype.joda.deser.DateTimeDeserializer;
import com.fasterxml.jackson.datatype.joda.ser.DateTimeSerializer;
import org.joda.time.DateTime;
import org.joda.time.ReadableInstant;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;



public class JacksonJodaTimeJavaExample
{
    private static final DateTimeFormatter DATE_TIME_FORMATTER =
        DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZZ");
    private static final JacksonJodaDateFormat JACKSON_JODA_DATE_FORMAT =
        new JacksonJodaDateFormat(DATE_TIME_FORMATTER);

    private static ObjectMapper mapper = createMapper();

    private static ObjectMapper createMapper()
    {
        return JsonMapper
            .builder()
            .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
            .addModule(new JodaModule()
                           // If you do not want to customize the formatting, you can remove the next two lines
                           .addSerializer(new DateTimeSerializer(JACKSON_JODA_DATE_FORMAT))
                           .addDeserializer(ReadableInstant.class, new DateTimeDeserializer(ReadableInstant.class, JACKSON_JODA_DATE_FORMAT))
            )
            // Enable pretty printing for our example
            .enable(SerializationFeature.INDENT_OUTPUT)
            .build();
    }

    record Event(
        DateTime startTime,
        DateTime endTime,
        @JsonFormat(pattern = "yyyy-MM-dd 'at' HH:mm:ss")
        DateTime dateTimeInAlternateFormat
    ) {}


    public static void main(String[] args) throws Exception
    {
        final DateTime now = DateTime.now();
        Event event = new Event(now, now.plusHours(1), now);

        String json = mapper.writeValueAsString(event);
        System.out.println(json);

        Event deserializedEvent = mapper.readValue(json, Event.class);
        System.out.println(deserializedEvent);
    }
}

Kotlin Example

import com.fasterxml.jackson.annotation.JsonFormat
import com.fasterxml.jackson.databind.SerializationFeature
import com.fasterxml.jackson.databind.json.JsonMapper
import com.fasterxml.jackson.datatype.joda.JodaModule
import com.fasterxml.jackson.datatype.joda.cfg.JacksonJodaDateFormat
import com.fasterxml.jackson.datatype.joda.deser.DateTimeDeserializer
import com.fasterxml.jackson.datatype.joda.ser.DateTimeSerializer
import org.joda.time.DateTime
import org.joda.time.ReadableInstant
import org.joda.time.format.DateTimeFormat

object JacksonJodaTimeKotlinExample
{
    private val DATE_TIME_FORMATTER = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZZ")
    private val JACKSON_JODA_DATE_FORMAT = JacksonJodaDateFormat(DATE_TIME_FORMATTER)
    private val mapper = createMapper()

    private fun createMapper() =
        JsonMapper
        .builder()
        .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
        .addModule(
            // If you do not want to customize the formatting, you can remove the "apply" block
            JodaModule().apply {
                addSerializer(DateTimeSerializer(JACKSON_JODA_DATE_FORMAT))
                addDeserializer(ReadableInstant::class.java, DateTimeDeserializer(ReadableInstant::class.java, JACKSON_JODA_DATE_FORMAT))
            })
        // Enable pretty printing for our example
        .enable(SerializationFeature.INDENT_OUTPUT)
        .build()

    data class Event(
        var startTime: DateTime? = null,
        var endTime: DateTime? = null,
        // If we want a DateTime in an alternate format, we can
        @JsonFormat(pattern = "yyyy-MM-dd 'at' HH:mm:ss")
        var dateTimeInAlternateFormat: DateTime? = null)

    fun runExample()
    {
        val now = DateTime.now()
        val event = Event(now, now.plusHours(1), now)
        val json = mapper.writeValueAsString(event)
        println(json)
        val deserializedEvent = mapper.readValue(json, Event::class.java)
        println(deserializedEvent)
    }
}

fun main()
{
    JacksonJodaTimeKotlinExample.runExample()
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文