【发布时间】:2017-05-16 19:16:32
【问题描述】:
此 Question 类的 json 序列化中缺少 Action 字段。我知道我正在查询的问题有一些操作,因为我在控制器返回之前查看了问题对象
@Entity
@Table
@Data
public class Question {
@Id
@GeneratedValue
@Column
private int id;
@Column
private String text;
@Column
private double weight;
@Enumerated(EnumType.STRING)
private TeamType teamType;
@Column
private Category cat;
@ManyToOne
@JsonBackReference(value="act-ques")
private Action action;
@OneToMany
@JsonManagedReference(value="ques-resps")
private Set<Response> response;
}
这里是动作类
@Entity
@Table
@Data
public class Action {
@Id
@Column
@GeneratedValue
private Long id;
@Enumerated(EnumType.STRING)
private ActionType actionType;
@Enumerated(EnumType.STRING)
private Category cat;
@OneToMany
@Fetch(FetchMode.JOIN)
@JsonManagedReference(value="act-ques")
private Set<Question> questions;
}
我有一个 ActionController 并为该类返回一个 json 字符串。为什么问题的 json 中缺少 Action 类?
这里是动作控制器
@RestController
@RequestMapping("api/actions")
public class ActionController {
@Autowired
private ActionService actService;
@GetMapping
public List<Action> getActions(@RequestParam Map<String, Object> params) {
List<Action> actions = actService.getAll();
return actions;
}
}
这里是问题控制器。当我在其中设置断点时,我可以看到问题对象中的操作,但返回的 json 没有它们的字段
@RestController
@RequestMapping("api/questions")
public class QuestionController {
@Autowired
private QuestionService questionService;
@GetMapping
public List<Question> getQuestions(@RequestParam Map<String, Object> params) {
List<Question> questions = questionService.getQuestions(params);
return questions;
}
}
【问题讨论】:
-
显示实际代码而不是一些不相关的(暂时)片段。
-
父表实体中需要指定joinColumns=@JoinColumn(name="ID")
-
因为您使用的是
@JsonBackReference(value="act-ques")。@JsonManagedReference是引用的前向部分——正常序列化的部分。@JsonBackReference是引用的后面部分——它将从序列化中省略。
标签: java spring-mvc spring-boot jackson