日期:2014-05-20  浏览次数:20978 次

jackSon序列化枚举为字节数组抛空指针异常
最近在使用jackson的时候遇到这样一个问题,jackson版本1.9.10
Java code

        ObjectMapper mapper = new ObjectMapper(new SmileFactory());
        mapper.setVisibility(JsonMethod.FIELD, Visibility.ANY);
        mapper.configure(SerializationConfig.Feature.USE_ANNOTATIONS, false);
        
        mapper.setAnnotationIntrospector(new NopAnnotationIntrospector());

                System.out.println(mapper.writeValueAsBytes(ViewTime.FOREVER));


调用writeValueAsBytes此方法将枚举转成字节的时候抛空指针异常,下面是异常信息
org.codehaus.jackson.map.JsonMappingException: [no message for java.lang.NullPointerException]
at org.codehaus.jackson.map.ser.StdSerializerProvider._serializeValue(StdSerializerProvider.java:625)
at org.codehaus.jackson.map.ser.StdSerializerProvider.serializeValue(StdSerializerProvider.java:256)
at org.codehaus.jackson.map.ObjectMapper._configAndWriteValue(ObjectMapper.java:2575)
at org.codehaus.jackson.map.ObjectMapper.writeValueAsBytes(ObjectMapper.java:2114)
at com.myproduct.mobileinternet.cmsinterface.pojo.Configure.main(Configure.java:61)
Caused by: java.lang.NullPointerException
at org.codehaus.jackson.smile.SmileGenerator.writeString(SmileGenerator.java:996)
at org.codehaus.jackson.map.ser.std.EnumSerializer.serialize(EnumSerializer.java:59)
at org.codehaus.jackson.map.ser.std.EnumSerializer.serialize(EnumSerializer.java:24)
at org.codehaus.jackson.map.ser.StdSerializerProvider._serializeValue(StdSerializerProvider.java:610)
... 4 more
只要注掉
mapper.configure(SerializationConfig.Feature.USE_ANNOTATIONS, false);

mapper.setAnnotationIntrospector(new NopAnnotationIntrospector());
这两行就不会出现此问题,求大神指点这是什么情况。
Java code


public enum ViewTime
{
    FOREVER(-1), SEVEN_DAY(0), ONE_MONTH(1),TWO_MONTH(2),THREE_MONTH(3),SIX_MONTH(4),ONE_YEAR(5);
    
    private int value;

    private ViewTime(int value)
    {
        this.value = value;
    }

    public int getValue()
    {
        return value;
    }
    
    public static ViewTime fromValue(int period)
    {
        switch(period)
        {
        case -1:
            return FOREVER;
        case 0:
            return SEVEN_DAY;
        case 1:
            return ONE_MONTH;
        case 2:
            return TWO_MONTH;
        case 3:
            return THREE_MONTH;
        case 4:
            return SIX_MONTH;
        case 5:
            return ONE_YEAR;
        }
        return null;
    }
    @Override
    public String toString()
    {
        return String.valueOf(value);
    }
}



------解决方案--------------------
jason解析配置问题,帮顶