【问题标题】:Spring REST Endpoint Returning String instead of JSONSpring REST端点返回字符串而不是JSON
【发布时间】:2019-11-01 15:26:33
【问题描述】:

以下端点将用户名作为字符串返回。

我将如何构造它以返回一个 json 对象,该对象包含一个以该字符串作为其值的键(例如,{"user":"joeuser"}?

@GetMapping(value = "/getUser", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> getUser() {
    HttpHeaders responseHeaders = new HttpHeaders();
    CustomUserAuthentication authentication = (CustomUserAuthentication) SecurityContextHolder.getContext().getAuthentication();
    return ResponseEntity.ok().headers(responseHeaders).body(String.valueOf(authentication.getPrincipal()));
}

【问题讨论】:

    标签: rest spring-security


    【解决方案1】:

    使用一些 Json 库(如 gson),构建 Json 对象并将其返回正文而不是字符串。确保响应内容类型为 application/json

    您也可以手动构建看起来像Json但内容必须如上的String。

    【讨论】:

    • 谢谢,AlexC。我应该澄清一下——我不想使用额外的库。想知道 Spring 是否有类似的东西我可以利用。
    【解决方案2】:

    Spring 可以做你想做的事,但你需要返回一些 Spring 需要编组为 JSON 的内容。来自我之前的回答:https://stackoverflow.com/a/30563674/48229

    @RequestMapping(value = "/json", method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public Map<String, Object> bar() {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("test", "jsonRestExample");
        return map;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-11
      • 2012-11-26
      • 2022-12-06
      • 2020-04-08
      • 2018-07-03
      • 2020-01-13
      相关资源
      最近更新 更多