我有一个Java映射,作为响应,我想使用DTO进行映射。我尝试过:
服务:
@Service
public class GatewaysService {
public Map<Integer, String> getGatewaysList() {
Map<Integer, String> list = new HashMap<>();
list.put(1, "Bogus");
return list;
}
}
API:
@Autowired
private GatewaysService gatewaysService;
@GetMapping("gateways")
public ResponseEntity<?> getGateways() {
return ok(gatewaysService.getGatewaysList().map(mapper::toGatewayMap));
}
DTO:
public class ContractGatewaysDTO {
private Integer id;
private String gateway;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getGateway() {
return gateway;
}
public void setGateway(String gateway) {
this.gateway = gateway;
}
}
映射器:
Map<Integer, String> toGatewayMap(ContractGatewaysDTO dto);
但是我得到了错误:
The method map(ContractDTO) in the type ContractsMapper is not applicable for the arguments (mapper::toGatewayMap)
映射它的正确方法是什么?我想将Java映射转换为键值响应。
答案 0 :(得分:3)
为什么不只是
@Autowired
private GatewaysService gatewaysService;
@GetMapping("gateways")
public Map<String,String> getGateways() {
return gatewaysService.getGatewaysList();
}
您不必在这里映射任何内容。
而且
除非在Java 9+中有所更改,否则我不记得java.uti.Map
拥有map
方法,就像您在此处使用它一样
gatewaysService.getGatewaysList().map(mapper::toGatewayMap)
我假设您试图做的事情是这样的:
List<Dto> yourlist= gatewaysService.getGatewaysList() //why MAP is named a LIST idk;
.entrySet() //can be any streamable collection - this comes with maps;
.stream()
.map(entry->new Dto(entry.key(),entry.value())
.collect(Collectors.toList());
答案 1 :(得分:1)
我在想的是,您可能希望将Map转换为DTO实体,如果需要的话,可以通过以下操作实现:
return ResponseEntity.ok(getGatewaysList()
.entrySet()
.stream()
.map( g -> new ContractGatewaysDTO(g.getKey(), g.getValue()))
.collect(Collectors.toList()));