使用Jackson将类序列化为JSON

使用Jackson将类序列化为JSON

本文介绍了使用Jackson将类序列化为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表示问卷的对象的结构,我需要序列化到JSON。
一类结构是一个OpenQuestion,这个类使用泛型与两个参数。
当所使用的类型之一是Date时,问题开始,日期被序列化错误,就像一个长的。

I have a structure of objects representing a Questionnaire and I need to serialize to JSON.One class of the structure is a OpenQuestion and this class use generics with two parameters.The problem starts when one of types used was Date, the date is serialized wrong, like a long.

类代码:

public class OpenQuestion <valueType,validationType> extends AbstractQuestion implements    Serializable {
    private valueType value;
    private validationType minValue;
    private validationType maxValue;
    ...
}

我看到了如何序列化日期哈希映射如果散列映射总是使用Date,但在这种情况下,我使用带有String,Integer或Date的类。

I saw how to serialize a date in a hash map if the hash map always uses a Date, but in this case I use the class with String, Integer or Date.

有什么想法来解决吗?
谢谢

Any idea to solve it?Thanks

推荐答案

如@MiserableVariable所指出的,Jackson将(大多数)日期字段序列化为(数字长)时间戳默认。您可以通过多种方式覆盖此行为。

As pointed out by @MiserableVariable, Jackson serializes (most) date fields as (numeric long) timestamps by default. You can override this behavior in a number of ways.

如果使用您自己的ObjectMapper实例,请覆盖属性以将日期写为ISO-8601:

If using your own instance of ObjectMapper, override a property to write dates as ISO-8601:

objectMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);

如果使用您自己的ObjectMapper实例,以自己的自定义格式写入日期:

If using your own instance of ObjectMapper, to have dates written in your own custom format:

objectMapper.setDateFormat(myDateFormat); // 1.8 and above
objectMapper.getSerializationConfig().setDateFormat(myDateFormat); // for earlier versions (deprecated for 1.8+)

为了保留大多数字段的默认序列化行为,但是要覆盖某些对象上的某些字段,请使用自定义序列化程序:

To leave the default serialization behavior for most fields, but override it for certain fields on certain objects, use a custom serializer:

public class MyBean implements Serializable {
    private Date postDate;

    // ... constructors, etc

    @JsonSerialize(using = MyCustomDateSerializer.class)
    public Date getPostDate() {
        return postDate;
    }
}

public class MyCustomDateSerializer extends JsonSerializer<Date> {

    @Override
    public void serialize(final Date date, final JsonGeneraror generator,
          final SerializerProvider provider) throws IOException,
          JSONProcessingException {

        generator.writeString(yourRepresentationHere);
    }
}

所有这些信息都可以在,其中大部分在部分处理日期处理。

All of this information is available in the Jackson Documentation, with the bulk of it in the section dealing with date handling.

这篇关于使用Jackson将类序列化为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!