json - 具有列表属性的杰克逊 JSON
问题描述
我的应用程序中有以下 2 个类:
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"}]
我已经验证了高尔夫球场都添加了洞。
知道问题可能是什么吗?
谢谢
解决方案
我设法通过使用@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}]}
推荐阅读
- java - 你如何在 Android 中操作多边形?
- python - 我只有一把钥匙,但需要根据评分提取对象
- javascript - Angular 中的 D3 力模拟
- deconvolution - 在pytorch中使用双线性插值进行反卷积(convTranspose2D)初始化?
- java - 使用 lambda 表达式查找 Recaman 序列的第 n 个值
- xamarin.forms - 在后端服务器请求上启动后台服务
- python - 如何在python列表中的map()中使用lambda if else?
- laravel - Laravel 为嵌套集合添加变量
- python - 递归函数返回无
- spring - Spring IoC:每个请求的标识符