SpringAPI返回文件而不是字符串

c90pui9n  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(309)

我有下面的代码作为api端点。我希望在访问端点时在浏览器上显示json字符串。
但是,当我访问端点时,会下载一个文件。名为api.json的文件包含 {"key": "myKey"} . 我不知道为什么它会生成一个文件。我能得到一些帮助吗?
谢谢!

@GetMapping(path="/getFields2", produces=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity getFieldssec(@Context HttpServletRequest httpServletRequest)
{
    return ResponseEntity.ok("{\"key\": \"myKey\"}");
}
z3yyvxxp

z3yyvxxp1#

您可以创建一个spring资源并返回它

@GetMapping(path="/getFields2", produces=MediaType.APPLICATION_JSON_VALUE)
public  ResponseEntity<Resource> getFieldssec(
        @Context HttpServletRequest httpServletRequest) {

    String text="{\"key\": \"myKey\"}";
    Resource resource = new ByteArrayResource(text.getBytes());

    return ResponseEntity.ok()
        .contentLength(text.length())
        .contentType(MediaType.APPLICATION_JSON)
        .body(resource);
}

相关问题