Jackson writeValueAsString()定期抛出JsonMappingException

时间:2016-06-27 22:36:28

标签: java jackson

看到定期调用writeValueAsString()以定期对JSON进行编组时抛出的定期异常...但是,它们在重试时始终有效......

这是由杰克逊的API(v2.7.5)在解析/封送(非空)Java Date值到JSON时抛出的......

这是我们的设置,它定义了类级别并在多个线程/请求中重用

private ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

和完整的堆栈跟踪......

com.fasterxml.jackson.databind.JsonMappingException: (was java.lang.ArrayIndexOutOfBoundsException) (through reference chain: MyIndex["createdAt"])
at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:232)
at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:197)
at com.fasterxml.jackson.databind.ser.std.StdSerializer.wrapAndThrow(StdSerializer.java:186)
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:640)
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:152)
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:541)
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:632)
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:152)
at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:114)
at com.fasterxml.jackson.databind.ObjectMapper._configAndWriteValue(ObjectMapper.java:2811)
at com.fasterxml.jackson.databind.ObjectMapper.writeValueAsString(ObjectMapper.java:2268) 

1 个答案:

答案 0 :(得分:0)

进一步的测试显示,根本原因是在杰克逊正在序列化的类的getter方法中使用SimpleDateFormatter是非线程安全的......所以杰克逊已经摆脱困境(而且我已经重新开始)......

更改为使用ThreadLocal<DateFormat>,一切都很好......

public class ThreadLocalDateFormat extends ThreadLocal<DateFormat>
{
    private String dateFormat;

    public ThreadLocalDateFormat(String dateFormat)
    {
        this.dateFormat = dateFormat;
    }

    @Override
    protected DateFormat initialValue()
    {
        return new SimpleDateFormat(dateFormat);
    }
}

感谢您的帮助...