我的应用程序中有以下两个类:
public class GolfCourse {
private int id;
@JsonBackReference
private List<Hole> holes;
......
}
public class Hole{
private int id;
@JsonManagedReference
private GolfCourse course;
......
}
当我尝试使用Jackson将一系列GolfCourse对象序列化为JSON时:
List<GolfCourse> courses
......(populate course)
String outputJSON = new ObjectMapper().writeValueAsString(golfCourses);
我最终得到的JSON数组只显示每个高尔夫球场的id属性,但它不包括孔列表:
[{"id":"9ed243ec-2e10-4628-ad06-68aee751c7ea","name":"valhalla"}]
我已经确认高尔夫球场都添加了洞。
知道问题可能是什么?
由于
答案 0 :(得分:2)
我使用@JsonIdentityInfo
注释设法获得了理想的结果:
@JsonIdentityInfo(
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "id")
public class GolfCourse
{
public int id;
public String name;
public List<Hole> holes;
}
@JsonIdentityInfo(
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "id")
public class Hole
{
public int id;
public String name;
public GolfCourse course;
}
测试方法:
public static void main(String[] args) {
Hole h1 = new Hole();
Hole h2 = new Hole();
GolfCourse gc = new GolfCourse();
h1.id = 1;
h1.name = "hole1";
h1.course = gc;
h2.id = 2;
h2.name = "hole2";
h2.course = gc;
gc.id = 1;
gc.name = "course1";
gc.holes = new ArrayList<>();
gc.holes.add(h1);
gc.holes.add(h2);
ObjectMapper mapper = new ObjectMapper();
try {
mapper.writeValue(System.out, gc);
} catch (Exception e) {
e.printStackTrace();
}
}
输出:
{"id":1,"name":"course1","holes":[{"id":1,"name":"hole1","course":1},{"id":2,"name":"hole2","course":1}]}