我有一个类需要使用 jackson 进行反序列化,并且该类有一个集合属性。该集合为空,但不为空。 问题:如何反序列化没有空集合的类。示例代码如下:
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 import 更好的支持这个版本的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>
最佳答案
您可以在您的类或文件中使用@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
}
关于java - 当 jackson 为空列表时不要返回属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15426232/