【问题标题】:Stack overflow error producing JSON with Spring MVC使用 Spring MVC 生成 JSON 的堆栈溢出错误
【发布时间】:2016-01-07 03:14:49
【问题描述】:

我正在尝试将 Java 对象转换为 JSON 并将其显示在网页上。正在发生的事情是 Plugs 被打印一次,而 Details 和 Users 被无限打印。

这是我尝试打印的方式

@RequestMapping(value = "/json/{userName}", method = RequestMethod.GET, produces = "application/json; charset=UTF-8")
@ResponseBody()
public List<Plugs> getPlugs(@PathVariable("userName") String userName) {
    User userInfo = userDAO.getUserInfo(userName);
    System.out.println("------Here's the thing------");
    System.out.println(userInfo.getDetails().getPlugs());
    return userInfo.getDetails().getPlugs();
}

这里是使用 JPA 的每个表之间的关系

//User.java
@OneToOne(fetch = FetchType.LAZY, mappedBy = "user")
private Details details;

--

//Details.java
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "username")
private User user;

@OneToMany(mappedBy = "details", targetEntity = Plugs.class)
private List<Plugs> plugs;

--

//Plugs.java
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "post_code", referencedColumnName = "post_code")
private Details details;

我已经在私有字段和 getter 上尝试过诸如 @JsonIgnore@JsonBackReference@JsonManagedReference 之类的方法(但也许有人可以告诉我如何再做一次)和 @JsonIdentityInfo (也许再次也有人可以帮我解决这个问题)。

问题:如何仅以 JSON 格式打印插头而不打印其他内容?

如果需要更多代码,我会提供更多。

【问题讨论】:

  • 分享您的确切堆栈跟踪。
  • JPA 与您的 JSON 生成有什么关系(即问题)?
  • @NeilStockton 什么都没有。我只是说我正在使用 JPA。
  • @NeilStockton 哦,我什至没有意识到 JPA 被标记了。对此感到抱歉

标签: java json spring spring-mvc


【解决方案1】:

解决了这个问题。这是我更改代码的地方

@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "username")
@JsonIgnore
@XmlTransient
private User user

--

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "post_code", referencedColumnName = "post_code")
@JsonIgnore
@XmlTransient
private Details details;

在每个实体的顶部,我放了这个

@JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, property = "@id")

【讨论】:

    猜你喜欢
    • 2019-02-19
    • 2010-11-14
    • 2014-01-26
    • 2019-02-16
    • 2011-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多