【发布时间】:2017-05-15 08:53:09
【问题描述】:
假设我有这个客户端 JSON 输入:
{
id: "5",
types: [
{id: "1", types:[]},
{id: "2", types:[]},
{id: "1", types[]}
]
}
我有这门课:
class Entity {
private String id;
private Set<Entity> types = new LinkedHashSet<>();
public String getId() {
return this.id;
}
public String setId(String id) {
this.id = id;
}
public Set<Entity> getTypes() {
return types;
}
@JsonDeserialize(as=LinkedHashSet.class)
public void setTypes(Set<Entity> types) {
this.types = types;
}
@Override
public boolean equals(Object o){
if (o == null || !(o instanceof Entity)){
return false;
}
return this.getId().equals(((Entity)o).getId());
}
}
我有这个 Java Spring 端点,我在 POST 请求的正文中传递输入:
@RequestMapping(value = "api/entity", method = RequestMethod.POST)
public Entity createEntity(@RequestBody final Entity in) {
Set<Entity> types = in.getTypes();
[...]
}
我想要:
Set<Entity> types = in.getTypes();
只有两个条目的顺序正确...因为其中一个是基于 id 的重复项... 相反,我在 LinkedHashSet (!) 中得到了重复项
我从我的代码中认为删除重复项会自动工作,但显然不是。
这个问题的背景比 Why do I need to override the equals and hashCode methods in Java? 因为它通过 Java Spring 使用隐式 Jackson 序列化。
【问题讨论】:
-
你的
hashCode()函数在哪里? -
和
equals(Object)一样是合同的一部分。 -
谢谢!看来我错过了 - 让我添加它,看看它是否有效
-
@GurwinderSingh 成功了!!您可以将其添加为答案,如果您愿意,我会接受:)
标签: java json spring-boot jackson