Jackson bug(或功能!?)在使用java.util.Set时 - mySet.size()始终为1 [英] Jackson bug (or feature!?) when using java.util.Set - mySet.size() is always 1
问题描述
我正在使用Jackson 2.2.0和Spring 3.2.0与Hibernate 4.2.2。
I am using Jackson 2.2.0 and Spring 3.2.0 with Hibernate 4.2.2.
我最近不得不通过POST将一组对象发送到服务器:
I recently had to send an array of objects via POST to the server:
{"cancelationDate":"2013-06-05",
"positions":[
{"price":"EUR 12.00",
"count":1},
{"price":"EUR 99.00",
"count":1}
]
}
我的课程如下:
public class Bill extends {
LocalDate cancelationDate;
Set<Position> positions;
...
}
和:
public class Position {
Integer count;
BigMoney price;
@JsonIgnore
Bill bill;
...
}
当我打电话给 bill.getPositions()。size()
它告诉我 1
。
When I call bill.getPositions().size()
it tells me 1
.
如果我使用列表< Position>
而不是设置< Position>
它很好用。那么设置
的问题是什么?
If I use List<Position>
instead of Set<Position>
it works nice. So what's the problem with Set
?
谢谢:)
public int hashCode() {
final int prime = 31;
int result = 1;
result = (int) (prime * result + ((id == null) ? 0 : id.hashCode()));
return result;
}
public boolean equals(Object obj) {
if (obj == this)
return true;
if (!(obj instanceof Position))
return false;
Position equalCheck = (Position) obj;
if ((id == null && equalCheck.id != null) || (id != null && equalCheck.id == null))
return false;
if (id != null && !id.equals(equalCheck.id))
return false;
return true;
}
推荐答案
由于id为null Jackson反序列化了Positions,hashCode为不同的对象返回相同的值,equals返回true。 Set不能包含相同的元素。修复你的equals / hashcode实现,一切都会正常工作。
Since id is null for the Jackson deserialized Positions, hashCode returns the same value for the different objects, and equals returns true. A Set cannot contain to elements which are equal. Fix your equals/hashcode implentation and everything will work as it should.
建议的新hashCode /等于:
Suggested new hashCode/equals:
public int hashCode() {
final int prime = 31;
int result = 1;
result = (int) (prime * result + ((id == null) ? 0 : id.hashCode()));
result = (int) (prime * result + ((price== null) ? 0 : price.hashCode()));
return result;
}
public boolean equals(Object obj) {
if (obj == this)
return true;
if (!(obj instanceof Position))
return false;
Position equalCheck = (Position) obj;
if ((id == null && equalCheck.id != null) || (id != null && equalCheck.id == null))
return false;
if (id != null && !id.equals(equalCheck.id))
return false;
if ((price== null && equalCheck.price != null) || (price != null && equalCheck.price == null))
return false;
if (price!= null && !price.equals(equalCheck.idprice)
return false;
return true;
}
这篇关于Jackson bug(或功能!?)在使用java.util.Set时 - mySet.size()始终为1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!