反序列化和多个反向引用属性,名称为' defaultReference'

时间:2015-02-05 00:43:40

标签: java json jackson

我正在尝试使用Jackson 1.9将嵌套的JSON对象反序列化为POJO,但我遇到了麻烦。下面是类以及我尝试解析的示例JSON字符串。

(省略了getters和setter)

JSON字符串:

sellerJson = "[{\"id\":\"1\",\"first_name\":\"Joe\",\"last_name\":\"Sellerman\",\"company\":\"NY CANYON RANCH\"," +
                    "\"prorated_sellers\":[{\"first_name\":\"Steve\",\"last_name\":\"Jobs\",\"company\":\"NY CANYON RANCH\"}," +
                    "{\"first_name\":\"Lorne\",\"last_name\":\"Michaels\",\"company\":\"NY CANYON RANCH\"}]," +
                    "\"pens\":[{\"id\":\"2\",\"pen_no\":\"902\"}]}]";

Java类:

@Table(name="seller")
public class SellerModel implements Serializable, Comparable<SellerModel> {

    private static final long serialVersionUID = 201302111531L;

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="id")  
    private Integer id;

    @Column()
    private String first_name;

    @Column()
    private String last_name;

    @Column()
    private String company;

    @Column()
    private Boolean is_prorated;

    @JsonIgnore
    @ManyToOne()
    @JoinColumn(name="parent_seller_id", referencedColumnName="id")
    private SellerModel parent_seller;

    @JsonManagedReference(value="seller-prorated")
    @OneToMany(mappedBy = "parent_seller", cascade={CascadeType.ALL}, orphanRemoval=true)
    private List<SellerModel> prorated_sellers;

    @JsonManagedReference(value="seller-pen")
    @OneToMany(mappedBy = "parent_seller", cascade={CascadeType.ALL}, orphanRemoval=true)
    private List<PenModel> pens;
}

@Table(name="pen")
public class PenModel implements Serializable, Comparable<PenModel> {

    private static final long serialVersionUID = 201302111537L;

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="id")  
    private Integer id;

    @Column()
    private String pen_no;

    @JsonBackReference(value="pen-seller")
    @ManyToOne()
    @JoinColumn(name="parent_seller_id", referencedColumnName="id")
    private SellerModel parent_seller;

    @JsonManagedReference(value="pen-livestock")
    @OneToMany(mappedBy = "parent_pen", cascade={CascadeType.ALL}, orphanRemoval=true)
    private List<LivestockModel> livestock;
}

但是,当我尝试执行反序列化时:

List<SellerModel> sellers = (List<SellerModel>) mapper.readValue(sellerJson, 
                    mapper.getTypeFactory().constructCollectionType(List.class, SellerModel.class));

我收到以下异常消息:

  

java.lang.IllegalArgumentException:多个反向引用属性   名称为“defaultReference”

我读到提供(value ='something-unique')注释属性应解决此问题,但我没有运气。有没有人有任何建议?

1 个答案:

答案 0 :(得分:2)

我至少看到两个问题。 第一:

  • SellerModel.prorated_sellers注明@JsonManagedReference(value="seller-pen")
  • PenModel.parent_seller注明@JsonBackReference(value="pen-seller")

它们必须具有相同的名称才能相关。

第二

  • SellerModel.parent_seller应使用@JsonManagedReference(value="seller-prorated")托管)进行注释,并删除@JsonIgnore注释
  • SellerModel.prorated_sellers应注明@JsonBackReference(value="seller-prorated")返回