java - spring 注解 @ResponseBody 返回JSON 能不能设置他不返回为 null 的值
PHP中文网
PHP中文网 2017-04-17 13:09:16
0
3
377

spring 注解 @ResponseBody 返回 JSON 能不能设置他不返回为 null 的值

java    @RequestMapping(value="/{username}",method=RequestMethod.GET,params="json")
    @ResponseBody
    public User show(@PathVariable String username) {
        return users.get(username);
    }
PHP中文网
PHP中文网

认证0级讲师

reply all(3)
巴扎黑

SetjacksonIgnorenull

<mvc:annotation-driven>
    <mvc:message-converters register-defaults="true">
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <property name="objectMapper">
                <bean class="com.fasterxml.jackson.databind.ObjectMapper">
                    <property name="serializationInclusion">
                        <value type="com.fasterxml.jackson.annotation.JsonInclude.Include">NON_NULL</value>
                    </property>
                </bean>
            </property>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>
小葫芦

You can use trinocular when displaying the page. If the read value is null, the empty character will be output

黄舟

It is best to control at the business coding level instead of using the unified entrance MappingJackson2HttpMessageConverter. The control here is a one-size-fits-all approach, which will cause a headache when you need to return null in another scenario.

@RequestMapping(value="/{username}",method=RequestMethod.GET,params="json")
@ResponseBody
public User show(@PathVariable String username) {
    User user = users.get(username);
    return user == null ? new User() : user; // 这里只要为null的时候,返回一个空的对象即可
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!