我有一个REST端点,我可以调用它请求一些数据,但是它在JSON响应中返回了3次相同的对象,而不是仅返回不同的结果。
这是我得到的答复:
[
{
"id": "5555 ",
"label": "MAIN USER (5555) "
},
{
"id": "5555 ",
"label": "MAIN USER (5555) "
},
{
"id": "5555 ",
"label": "MAIN USER (5555) "
}
]
这是用于生成JSON响应的控制器:
@RestController
public class AutoCompleteController {
private AutoCompleteService autoCompleteService;
private EntityManager em;
public AutoCompleteController(AutoCompleteService autoCompleteService, EntityManager em) {
this.autoCompleteService = autoCompleteService;
this.em = em;
}
@RequestMapping(value = "jobs", method = RequestMethod.GET)
public @ResponseBody
List<AutoComplete> getSalary(@RequestParam(value = "autocomplete") String autocompleteValue) {
return autoCompleteService.retrieveSalary(autocompleteValue);
}
}
依次,控制器调用AutoCompleteService
:
@Service
public class AutoCompleteService {
private AutoCompleteRepository autocompleteRepository;
public AutoCompleteService(AutoCompleteRepository autRepo) {
this.autocompleteRepository = autRepo;
}
public List<AutoComplete> retrieveSalary(String jobClassCd) {
List<AutoComplete> salaries = autocompleteRepository.findAllByJobClassCdIsContaining(jobClassCd);
if (salaries.size() <= 0) {
throw new AutoCompleteNotFoundException(jobClassCd);
}
return salaries;
}
}
答案 0 :(得分:0)
只需确保您的方法autoCompleteService.retrieveSalary仅返回1个结果,然后根据您的过滤器检查数据库是否存在内容相同的多行。 如果您始终希望得到1个结果,则使您返回一个Object,而不是List <>。
答案 1 :(得分:0)
假设您的请求是在Java代码中对来自自动完成服务的信息进行重复数据删除,那么可以选择将信息转换为Set,然后返回到列表。假设正确设置哈希码和等于条件,这将仅返回一个唯一的结果。
import java.util.*;
class AutoComplete {
// Not using getter / setters just for convenience here
public String id;
public String label;
public AutoComplete(String id, String label) {
this.id = id;
this.label = label;
}
@Override
public boolean equals(Object other) {
if (other instanceof AutoComplete) {
AutoComplete o = (AutoComplete) other;
return o.id.equals(this.id) && o.label.equals(this.label);
}
return false;
}
@Override
public int hashCode() {
return (this.id + "-" + this.label).hashCode();
}
public String toString() {
return this.id + " -- " + this.label;
}
}
class Main {
public static void main(String[] args) {
ArrayList<AutoComplete> initialList = new ArrayList<AutoComplete>();
initialList.add(new AutoComplete("555", "MAIN"));
initialList.add(new AutoComplete("555", "MAIN"));
initialList.add(new AutoComplete("555", "MAIN"));
System.out.println(initialList);
HashSet<AutoComplete> deduped = new HashSet<AutoComplete>(initialList);
List<AutoComplete> dedupedList = new ArrayList<AutoComplete>(deduped);
System.out.println(dedupedList);
}
}