jackson-databind
jackson-databind copied to clipboard
Combination of JsonMerge and JsonManagedReference fails
I have an issue where if I use a List with both JsonMerge and JsonManagedReference annotations, the back reference is null.
I came up with the following test case:
Test class
package com.carvajalonline;
import java.util.List;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Test {
public static void main(String[] args) {
ObjectMapper objectMapper = new ObjectMapper();
try {
Invoice invoice = objectMapper.readValue("{\"lines\": [{\"id\": 20, \"total\": \"$200.00\"}]}", Invoice.class);
List<InvoiceLine> lines = invoice.getLines();
for (InvoiceLine invoiceLine : lines) {
System.out.println("line: " + invoiceLine.getId() + " - " + invoiceLine.getInvoice());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Invoice class
package com.carvajalonline;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import com.fasterxml.jackson.annotation.JsonMerge;
public class Invoice {
@JsonManagedReference("invoice")
@JsonMerge
private List<InvoiceLine> lines = new ArrayList<>();
public Invoice() {
lines.add(new InvoiceLine(10, "$100.00", this));
}
public List<InvoiceLine> getLines() {
return lines;
}
public void setLines(List<InvoiceLine> lines) {
this.lines = lines;
}
}
InvoiceLine class
package com.carvajalonline;
import com.fasterxml.jackson.annotation.JsonBackReference;
public class InvoiceLine {
private Integer id;
private String total;
@JsonBackReference("invoice")
private Invoice invoice;
public InvoiceLine() {
}
public InvoiceLine(Integer id, String total, Invoice invoice) {
this.id = id;
this.total = total;
this.invoice = invoice;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTotal() {
return total;
}
public void setTotal(String total) {
this.total = total;
}
public Invoice getInvoice() {
return invoice;
}
public void setInvoice(Invoice invoice) {
this.invoice = invoice;
}
}
I expect the output to be:
line: 10 - com.carvajalonline.Invoice@XXXX line: 20 - com.carvajalonline.Invoice@XXXX
However, when I introduce the JsonMerge annotation, the output I get is: line: 10 - com.carvajalonline.Invoice@XXXX line: 20 - null (SHOULD NOT BE GETTING NULL HERE)
If I remove the JsonMerge annotation, I get this output line: 20 - com.carvajalonline.Invoice@XXXX
Obviously when the JsonMerge annotation is removed, line 10 no longer appears because the array is being replaced, however the invoice is no longer null.
I am using version 2.9.5 to produce this bug. Any pointers as to how this can be handled?
Thanks!