映射 Java DTO 作为响应

Map Java DTO in response

我有一个 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 映射转换为键值响应。

为什么不只是

@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());

我的想法是,您可能希望将 Map 转换为 DTO 实体,如果需要,您可以这样做:

return ResponseEntity.ok(getGatewaysList()
                                    .entrySet()
                                    .stream()
                                    .map( g -> new ContractGatewaysDTO(g.getKey(), g.getValue()))
                                    .collect(Collectors.toList()));