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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3269459/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 19:10:51  来源:igfitidea点击:

How to serialize Joda DateTime with Hymanson JSON processor?

javajsonjodatimeHymanson

提问by Haywood Jablomey

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

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

I've tried:

我试过了:

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

I've also tried:

我也试过:

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

Thanks!

谢谢!

回答by Rusty Kuntz

In the object you're mapping:

在您映射的对象中:

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

In CustomDateSerializer:

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

回答by Moesio

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

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 Hymanson you can configure your spring as follow:

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

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

<bean id="HymansonSerializationConfig" class="org.codehaus.Hymanson.map.SerializationConfig"
    factory-bean="HymansonObjectMapper" 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.

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

回答by Kimble

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

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

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

Maven dependency:

Maven 依赖:

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

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

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

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

二进制文件:http: //repo1.maven.org/maven2/com/fasterxml/Hymanson/datatype/Hymanson-datatype-joda/

回答by ydrozhdzhal

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

似乎对于 Hymanson 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);
    }
}

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

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

Approach proposed by Rusty Kuntz works perfect for my case.

Rusty Kuntz 提出的方法非常适合我的情况。

回答by oggmonster

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

正如@Kimble 所说,对于 Hymanson 2,使用默认格式非常容易;只需JodaModule在您的ObjectMapper.

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

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

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

For example, here's a DateTimeserializer that uses the ISODateFormatwith the UTC time zone:

例如,这是一个DateTime使用ISODateFormatUTC 时区的序列化程序:

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:

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

回答by Atais

The easy solution

简单的解决方案

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

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

I simply used the pattern in@JsonFormatannotation

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

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

基本上我的班级有一个DateTime字段,所以我在 getter 周围添加了一个注释:

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

I serialize the class with ObjectMapper

我用 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 Hymanson 2.5.4

我们使用Hyman逊 2.5.4

回答by jgeerts

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

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

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

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

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

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

回答by Luciana Campello

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

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

Add the dependency on pom.xml

添加依赖 pom.xml

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

and add JodaModule on your ObjectMapper

并在您的上添加 JodaModule ObjectMapper

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

回答by Stephan

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

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

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

JSON output:

JSON 输出:

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