当它是带有杰克逊的空列表时,不要返回属性

2022-09-01 13:36:09

我有一个类需要使用 jackson 进行 dessrial 化,并且该类具有集合属性。集合为空,但不是空。问:如何在不带空集合的情况下反序列化类。示例代码如下:

class Person
{
    String name;
    List<Event> events;
    //....getter, setter
}

如果

person.list = new List<Event>(); 
persion.name = "hello";

然后除了json将是:

{name: "hello"}

{name: "hello", events:[]}

如何制作?谢谢~~

================================================

我已经通过n1ckolas的建议解决了这个问题。首先谢谢你。我的 jackson 版本是 2.1.1,Spring-3.2.2 导入了对这个 jackson 版本更好的支持。此外,这适用于数组和集合。以下是我的配置:

<!-- Enables the Spring MVC @Controller programming model -->
<mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <property name="objectMapper" ref="objectMapper"/>
        </bean>
    </mvc:message-converters>        
</mvc:annotation-driven>

<!--Json Mapper-->
<bean name="objectMapper" class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean" autowire="no">
    <property name="featuresToDisable">
        <list>
            <!--not to return empty colletion-->
            <value type="com.fasterxml.jackson.databind.SerializationFeature">WRITE_EMPTY_JSON_ARRAYS</value>
        </list>
    </property>
</bean>

答案 1

您可以在类或归档中使用@JsonInclude(JsonInclude.Include.NON_EMPTY) 注释。

import com.fasterxml.jackson.annotation.JsonInclude;
@JsonInclude(JsonInclude.Include.NON_EMPTY)
class Person
{
    String name;
    List<Event> events;
    //....getter, setter
}

答案 2

如果您可以使用 Jackson 注释更改原始模型,则可以通过以下方法实现此目的。

杰克逊有WRITE_EMPTY_JSON_ARRAYS。你可以用以下方式关闭它:

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

但它仅适用于 ,但不适用于 。但是,您可以结合使用 ,如下所示:ArraysCollections@JsonProperty@JsonIgnore

//....getter, setter of Person class
@JsonIgnore
public List<Event> getEvents() {
    return events;
}

@JsonProperty("events")
public Event[] getEventsArr() {
    return events.toArray(new Event[0]);
}

之后,您将获得输出,如您所料。

编辑:如果您使用的是SpringMVC,那么您可以在以下位置使用显式引用配置实际:ObjectMappermvc:annotation-driven

<!-- Configures the @Controller programming model -->
<mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
            <property name="objectMapper" ref="objectMapper"/>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

<!--custom Json Mapper configuration-->
<bean name="objectMapper" class="org.springframework.http.converter.json.JacksonObjectMapperFactoryBean" autowire="no">
    <property name="featuresToDisable">
        <list>
            <!--Ignore unknown properties-->
            <value type="org.codehaus.jackson.map.SerializationConfig.Feature">WRITE_EMPTY_JSON_ARRAYS</value>
        </list>
    </property>
</bean>

Offtop:通常指定 的显式实例非常有用,因为:ObjectMapper

  • 您可以按照自己的方式进行配置
  • 你可以通过以下方式使用它的引用@Autowired