与JSON

时间:2017-04-01 12:14:49

标签: java json serialization jackson

我有2个与一对多关系的POJO:

Receipt.java

@Entity   
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property="receiptId")
public class Receipt implements Serializable {    

    private long receiptId;        
    private int receiptNumber;

    @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.REMOVE)
    @JoinColumn(name = "receiptid")
    private List<Sales> sales;

//getters and setters
}

Sales.java

@Entity    
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "salesId")
public class Sales implements Serializable {

    private long salesId;
    private String salesProduct;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "receiptid", nullable = false)
    private Receipt receipt;

//getters and setters
}

我有2个简单的查询。第一个必须退回收据及其销售,第二个必须退回销售及其收据。如果我使用@JsonBackReference和@JsonManagedReference注释,那么只有一个查询正常工作。

当我使用@JsonIdentityInfo注释时,我得到了带有不必要的普通id号的序列化JSON。就像这个JSON末尾的数字122一样:

[{"receiptId":122,
"receiptNumber":2,
"sales":[{
    "salesId":2,
    "salesProduct":"product1"
    ,"receipt":122},
    {
    "salesId":4,
    "salesProduct":"product2"
    ,"receipt":122}]},
122]

这个JSON结尾处的数字4:

[{"salesId":2,
"salesProduct":"product1",
"receipt":
   {"receiptId":122,
   "receiptNumber":2,
   "sales":[
        2,
        {"salesId":4,
         "receipt":122,
         "salesProduct":"product2",
        }]
    }
},
4]

如何从服务器获取正确的JSON?

由于

更新1: 预期的JSON:

[{
"salesId":2,
"salesProduct":"product1",
"receipt":
   {"receiptId":122,
   "receiptNumber":2,
   "sales":[2,4]
    }
},
{"salesId":4,     
"salesProduct":"product2"
"receipt":
   {"receiptId":122,
   "receiptNumber":2,
   "sales":[2,4]
    }
}]

0 个答案:

没有答案