如何在 SpringBoot application.properties 文件中软编码映射

所以,我想返回一个应该如下所示的 JSON 对象:


{"Issues":[{"IssueName": "Loan"},{"IssueName": "Lease"},{"IssueName": "Other"}]}

到目前为止,我最接近这种格式的是通过这段代码:


@RequestMapping(value="/issueTypes", produces = MediaType.APPLICATION_JSON_VALUE)

    public  Map<String, String> getIssue(){

        HashMap<String, String> issue = new HashMap<>();

        issue.put("issues", "Loan");

        issue.put("issues", "Lease");

        issue.put("issues", "Other");

        return issue;

    }

虽然 map 在大括号中为我提供了键值对,但它不允许我将相同的键设置为不同的值(原因很明显)。还有其他方法可以返回上述 JSON 对象吗?是否可以对其进行软编码,application.properties以便以后我想添加更多问题类型时可以轻松完成?


繁花如伊
浏览 73回答 1
1回答

陪伴而非守候

一种方法是使用Listof Entries 而不是Mapof Entries:@Value("#{'${issues}'.split(',')}")private List<String> issues;@RequestMapping(value = "/issueTypes", produces = MediaType.APPLICATION_JSON_VALUE)public Map<String, List<Map.Entry<String, String>>> getIssue() {&nbsp; &nbsp; Map<String, List<Map.Entry<String, String>>> m = new LinkedHashMap<>();&nbsp; &nbsp; m.put("Issues", issues.stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .map(s -> Map.entry("issueName", s))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.toList()));&nbsp; &nbsp; return m;}在你的 application.properties 中:issues=Loan,Lease,Other输出:{"Issues":[{"issueName":"Loan"},{"issueName":"Lease"},{"issueName":"Other"}]}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java