2015-02-05 50 views
3

我想將一個嵌套的JSON對象反序列化爲使用Jackson 1.9的POJO,但是我遇到了麻煩。下面是我正在嘗試解析的示例JSON字符串的類。反序列化和多個反向引用屬性的名稱爲'defaultReference'

(getter和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」

,我讀了提供(值=「的東西,獨特的」)註解屬性應該解決這個問題,但我沒有任何運氣。有沒有人有什麼建議?

回答

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")返回
來註釋
相關問題