usercontroller.java

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

    }


user.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放在吸气剂而不是字段上,例如

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

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

10-11 00:04