首页 > 解决方案 > 具有列表属性的杰克逊 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"}]

我已经验证了高尔夫球场都添加了洞。

知道问题可能是什么吗?

谢谢

标签: jsonjackson

解决方案


我设法通过使用@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}]}

推荐阅读