Spring @JsonIgnore无法正常工作

如何让@JsonIgnore工作我有一堂课。 即使我把注释放在那里它对输出也没有影响。 我在用jackson。

public class QuestionBlock implements ComparableByID{ int ID; String title; String description; boolean deleted; boolean isDraft; boolean visible; Timestamp modifiedDate; String modifiedBy; private List questions = new ArrayList(); @JsonIgnore private List surveys = new ArrayList(); ... @JsonIgnore public List getSurveys() { return surveys; } @JsonIgnore public void setSurveys(List surveys) { this.surveys = surveys; } } 

这是我的Controller方法:

 @RequestMapping(value = "/questionBlock/{id}",produces = "application/json;charset=UTF-8") @ResponseBody public QuestionBlock getQuestionBlock(@PathVariable("id") int id) { return surveyService.getQuestionBlock(id); } 

这是我的servlet-context.xml:

                         com.adam.czibere     hibernate.dialect=org.hibernate.dialect.MySQLDialect                                            

我终于找到了解决方案。 我更改了import语句

 import org.fasterxml.jackson.annotate.JsonIgnore; 

 import org.codehaus.jackson.annotate.JsonIgnore; 

基本上你必须确保你到处使用同一个类。

注释应该只在’get’方法上。 你似乎在你的私人领域有@Json …注释。

如果您正在使用Jackson的实现并且其注释不起作用,那可能是因为您有更好的优先级的jackson的另一个依赖。 因此,如果你想确保jackson盛行的某些实现(恕我直言,最好的选择就是你已经注释过所有类的那个,因为可能它带有其他依赖项)在应用程序模块的pom中指定这种依赖。 因此,如果您在多个模块中拥有所有注释的实体

 import org.fasterxml.jackson.annotate.JsonIgnore; 

而不是替换所有导入只需在应用程序pom中指定相应的依赖项:

   com.fasterxml.jackson.core jackson-databind  

这将向Spring Boot阐明这是您要使用的实现。

您需要更改org.codehaus.jackson版本。 我目前正在使用1.1.1版本,其中@JsonIgonre无效。 我用1.9.13更改了它,然后@JsonIgnore工作正常。

   org.codehaus.jackson jackson-jaxrs 1.1.1  Change to  org.codehaus.jackson jackson-jaxrs 1.9.13  

而Java代码是: –

 import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import org.codehaus.jackson.annotate.JsonIgnore; @Entity @Table(name="users") public class Users implements Serializable{ @Id @GeneratedValue(strategy=GenerationType.AUTO) private Integer id; private String username; private String firstname; @JsonIgnore private String lastname; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getLastname() { return lastname; } public void setLastname(String lastname) { this.lastname = lastname; } } 

在使用spring和hibernate时我遇到了同样的问题。 原因是在实体类中我使用的是org.codehaus.jackson.JsonIgnore,而在spring我使用的是com.fasterxml.jackson.jaxrs.JsonIgnore。 修复两个层中的任何一个库,问题将消失。