【问题标题】:Return list from Spring rest apiSpring rest api 的返回列表
【发布时间】:2018-12-16 16:43:35
【问题描述】:

我想从 Spring rest api 返回 List:

@GetMapping("merchant_country")
    public ResponseEntity<?> getMerchantCountry() {
        return ok(Contracts.getSerialversionuid());
    }

我想从这里获取内容:

private Map<String, Object> getCountryNameCodeList() {

        String[] countryCodes = Locale.getISOCountries();
        Map<String, Object> list = new HashMap<>();

        for (String countryCode : countryCodes) {

            Locale obj = new Locale("", countryCode);

            list.put(obj.getDisplayCountry().toString(), obj.getCountry());
        }

        return list;
    }

如何映射结果?

【问题讨论】:

  • 您要返回地图或列表吗?两种方法之间没有关系吗?
  • 好的,当我从角码调用 GET 商人国家时,如何将 getCountryNameCodeList 作为地图返回?
  • 你不能把列表设置为地图的值吗?
  • 这是开始的好地方spring.io/guides/tutorials/rest@PeterPenzov

标签: java spring spring-boot response httpresponse


【解决方案1】:

当您需要对 HTTP 响应进行更多控制时(例如设置 HTTP 标头、提供不同的状态代码),请使用 ResponseEntity

在其他情况下,您可以简单地返回一个 POJO(或一个集合),然后 Spring 将为您处理所有其他事情。

class Controller {

    @Autowired
    private Service service;

    @GetMapping("merchant_country")
    public Map<String, Object> getMerchantCountry() {
        return service.getCountryNameCodeList();
    }

}

class Service {

    public Map<String, Object> getCountryNameCodeList() { ... }

}

Locate#getCountry 返回String,所以它可能是Map&lt;String, String&gt;

【讨论】:

    【解决方案2】:

    希望这会有所帮助,您必须按照 Andrew 的建议创建 ResponseEntity

    class controller{
    @Autowired
        private Service service;
    @GetMapping("merchant_country")
        public ResponseEntity<?> getMerchantCountry() {
            return service.getCountryNameCodeList();
        }`enter code here`
    }
    class service
    {
    private ResponseEntity<Map<String, Object>> getCountryNameCodeList() {
    
            String[] countryCodes = Locale.getISOCountries();
            Map<String, Object> list = new HashMap<>();
    
            for (String countryCode : countryCodes) {
    
                Locale obj = new Locale("", countryCode);
    
                list.put(obj.getDisplayCountry().toString(), obj.getCountry());
            }
    
            return new ResponseEntity<>(list, HttpStatus.OK);
        }
    

    【讨论】:

      猜你喜欢
      • 2022-10-25
      • 1970-01-01
      • 2016-08-03
      • 1970-01-01
      • 1970-01-01
      • 2018-10-23
      • 2018-11-06
      • 2017-06-27
      • 1970-01-01
      相关资源
      最近更新 更多