【问题标题】:Why objectMapper fails if I put a method different to set and get property in Java?如果我在 Java 中使用不同的方法来设置和获取属性,为什么 objectMapper 会失败?
【发布时间】:2017-03-29 18:33:43
【问题描述】:

我有一个名为 Car 的类,它代表一个实体,它有一个属性可以让我知道车门是否打开。

private int doorsOpened;
public void setDoorsOpened( val ) { this.doorsOpened = val; }
public int getDoorsOpened() { return this.doorsOpened; }

当我需要知道这一点时,我只需调用:

if (car.getDoorsOpened() != 0) {
    car.startAlarm();
}
else {
    car.allIsFine();
}

但是,我不想使用getDoorsOpened() != 0 比较,因此我创建了一个名为doorsOpened() 的新方法,它为我带来了布尔值:

public boolean doorsOpened() { return this.doorsOpened != 0; }

但是当我想使用这种新方法时:

String carData = objectMapper.writeValueAsString( car ); 

我得到了这个例外:

Unhandled server exception: (was java.lang.NullPointerException) (through reference chain: com.desafioguerreros.artifacts.car.entities.Car["volunteer"])
com.fasterxml.jackson.databind.JsonMappingException: (was java.lang.NullPointerException) (through reference chain: com.desafioguerreros.artifacts.car.entities.Car["volunteer"])
    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:187)
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:647)
    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:2866)
    at com.fasterxml.jackson.databind.ObjectMapper.writeValueAsString(ObjectMapper.java:2323)

为什么?

【问题讨论】:

    标签: java json string object jackson


    【解决方案1】:

    首先,查看堆栈跟踪,看起来实体中的一个属性为空,它导致了异常。如果我的理解是正确的,如果你有一个非常规的 getter,Jackson 只会忽略该字段而不抛出任何异常。如果您想拥有一个自定义 getter 并将该字段包含在序列化中,您可以使用@JsonProperty,如下所示。

    public class car{
        private int doorsOpened;
    
        @JsonProperty(value="doorsOpened")
        public boolean doorsOpened(){
            return this.doorsOpened != 0; 
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2011-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-24
      • 1970-01-01
      • 2020-06-01
      • 2012-10-30
      相关资源
      最近更新 更多