user1154644
user1154644

Reputation: 4609

Jackson JSON with list attribute

I have the following 2 classes in my application:

public class GolfCourse {
    private int id;
    @JsonBackReference
    private List<Hole> holes;
    ......
}


public class Hole{
   private int id;
   @JsonManagedReference
   private GolfCourse course;
   ......
}

When I try to serialize a list of GolfCourse objects as JSON using Jackson:

List<GolfCourse> courses
......(populate course)
String outputJSON = new ObjectMapper().writeValueAsString(golfCourses);

I end up with a JSON array that only shows the id attribute for each of the golf courses, but it does not include the hole list:

[{"id":"9ed243ec-2e10-4628-ad06-68aee751c7ea","name":"valhalla"}]

I have verified that the golf courses all have holes added.

Any idea what the issue may be?

Thanks

Upvotes: 0

Views: 744

Answers (1)

Sharon Ben Asher
Sharon Ben Asher

Reputation: 14328

I managed to get desired result by using @JsonIdentityInfo annotation:

@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;
}

test method:

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();
    }
}

output:

{"id":1,"name":"course1","holes":[{"id":1,"name":"hole1","course":1},{"id":2,"name":"hole2","course":1}]}

Upvotes: 2

Related Questions