本文介绍了杰克逊注释在 Spring 中被忽略的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图隐藏域类中的属性,但它一直出现在输出的 JSON 中.我正在使用 Jackson 2.0 和 Spring 3.1.1

I'm trying to make a property in a domain class hidden but it keeps appearing in the outputted JSON. I'm using Jackson 2.0 and Spring 3.1.1

/users/1 的输出:

Output of /users/1:

{"id":1,"password":null,"email":"[email protected]","firstName":"John","lastName":"Smith"}

我的域类:

@Entity
public class User {
    private String mPassword;
    ...
    @JsonIgnore
    public String getPassword() {
        return mPassword;
    }

    public void setPassword(String password) {
        mPassword = password;
    }
    ...
}

我的 springmvc 配置:

My springmvc config:

...
<mvc:annotation-driven/>
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
    <property name="favorPathExtension" value="true" />
    <property name="mediaTypes">
        <map>
            <entry key="json" value="application/json"/>
        </map>
    </property>
    <property name="defaultContentType" value="application/json"/>
    <property name="defaultViews">
        <list>
            <bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
        </list>
    </property>
</bean>
...

还有我的控制器:

@Controller
@RequestMapping("/users")
public class UserController {
    private UserService mUserService;

    public UserController(){}

    @Inject
    public void setUserController(UserService userService){
        mUserService=userService;
    }

    @RequestMapping(value="/{id}", method=RequestMethod.GET)
    public void getUser(@PathVariable("id") long id, Model model){
        model.addAttribute(mUserService.getUser(id));
    }
}

推荐答案

问题是 Spring 不支持 Jackson 2.0.已通过以下方式解决此问题:

The problem is that Spring doesn't work with Jackson 2.0. This has been solved in the following way:

<bean id="jacksonMessageConverter"
          class="own.implementation.of.MappingJacksonHttpMessageConverter"/>

<bean class="org.springframework.web.servlet.mvc
             .annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="jacksonMessageConverter"/>
            </list>
        </property>
        <property name="requireSession" value="false"/>
    </bean>

而 own.implementation.of.MappingJacksonHttpMessageConverter 基于此:

And the own.implementation.of.MappingJacksonHttpMessageConverter is based on this:

http://www.jarvana.com/jarvana/view/org/springframework/spring-web/3.0.0.RELEASE/spring-web-3.0.0.RELEASE-sources.jar!/org/springframework/http/converter/json/MappingJacksonHttpMessageConverter.java?format=ok

但是使用来自 Jackson 2.0 而不是 Jackson 1.* 的 ObjectMapper 和其他 Jackson 类.*

But use ObjectMapper and other Jackson classes from Jackson 2.0 instead of Jackson 1.*

这篇关于杰克逊注释在 Spring 中被忽略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 17:56