java - @jsonignore 在 spring mvc 中没有按预期工作

标签 java json spring spring-mvc

用户 Controller .java

@RequestMapping("/listusersjson")
    public ResponseEntity<Iterable<User>> getListofUsersJson() {
        Iterable<User>   users = userService.listUser(); 
        return new ResponseEntity<>(users, HttpStatus.OK);

    }

用户.java

@Entity
public class User {

    @Id
    @GeneratedValue
    @Column(name="user_id")
    private Integer id;

    private String name;

    private String email;

    private String password;

    private int enabled;

    public User(Integer id) {
        super();
        this.id = id;
    }


    public User() {
        super();
    }

    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "user_role", joinColumns = { @JoinColumn(name = "user_id") }, inverseJoinColumns = {
            @JoinColumn(name = "role_id") })
    @JsonIgnore
    private List<Role> roless;

    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
    @JsonIgnore
    private List<Cart> carts ;


    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
    @JsonIgnore
    private List<OrderDetails> orderDetails ;

}

异常

 HTTP Status 500 - Could not write JSON: failed to lazily initialize a collection of role: com.addtocart.dto.User.roless, could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]->com.addtocart.dto.User["roles"]); nested exception is org.codehaus.jackson.map.JsonMappingException: failed to lazily initialize a collection of role: com.addtocart.dto.User.roless, could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]->com.addtocart.dto.User["roles"])

即使我在所有存在一对一关系和延迟初始化异常可能性的必填字段上添加了 @jsonignore ,但我仍然收到上述异常。我不知道我错过了什么.

最佳答案

尝试将 @JsonIgnore 放在 getters 而不是字段上,例如

@JsonIgnore
public List<Cart> getCarts() {...}

关于java - @jsonignore 在 spring mvc 中没有按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35452586/

相关文章:

java - OS X 10.10 中使用 Oracle 的 1.8.0 JVM 时出现 "No Java runtime"错误

javascript - JSON 和 JavaScript - 如何使用 json 读取我的列表

java - 无法从 Spring RestController 获取 POST 数据

java - 如何使用 jpa 规范向子查询添加和构建动态谓词?

java - @Async 与 Spring 3.0.6

java - 如何制作可扩展的ArrayList?

java - RESTEasy - javax.ws.rs.NotFoundException : Could not find resource for full path

java - Intellij 断点不停止

c# - 解析 JSON 时使用动态关键字

json - 如何使用 JDBC 将 JSON 字段识别为 JSON 类型