[英]What is the best way to return primitive types/wrappers in Spring Controller?
When I return Integer or other wrapper from my Spring Controller like that:当我像这样从 Spring Controller 返回 Integer 或其他包装器时:
@GetMapping(path = "test1")
public Integer test1() {
return 1;
}
The response to the user has the following body:对用户的响应具有以下正文:
1
It's not a valid JSON.它不是有效的 JSON。 Are there any practices on how such values should be returned?
是否有关于如何返回这些值的做法? The concern is that I want my all API to return a valid JSON.
问题是我希望我的所有 API 都返回一个有效的 JSON。 I created a wrapper that returns:
我创建了一个返回的包装器:
{
"value": 1
}
But, maybe there is a better way to tackle these cases?但是,也许有更好的方法来处理这些情况?
If the return value is returned as plain text, eg a String
is returned without double-quotes, then the following would be true:如果返回值返回为纯文本,例如
String
返回没有双引号,则以下将是真实的:
You use @RestController
or @ResponseBody
您使用
@RestController
或@ResponseBody
Your code doesn't specify a response content type您的代码未指定响应内容类型
The client prefers text response over JSON response客户端更喜欢文本响应而不是 JSON 响应
To force the response to JSON, you need to tell Spring by specifying:要强制响应 JSON,您需要通过指定来告诉 Spring:
@GetMapping(path = "test1", produces = "application/json")
or或者
@GetMapping(path = "test1", produces = MediaType.APPLICATION_JSON_VALUE)
Since your response is just a number, you could decide that it is just that, and not JSON, by specifying eg text/plain
as the response content type.由于您的响应只是一个数字,您可以通过指定例如
text/plain
作为响应内容类型来决定它就是那个数字,而不是 JSON。 As with any other response, it is up to the client to correctly interpret the response value.与任何其他响应一样,正确解释响应值取决于客户端。
However, the plain 1-byte response 1
is valid JSON, so you can keep that, or you can do the { "value": 1 }
JSON response if you want.但是,普通的 1 字节响应
1
是有效的 JSON,因此您可以保留它,或者您可以根据需要执行{ "value": 1 }
JSON 响应。 It is your API, so you get to decide what the response format is.这是您的 API,因此您可以决定响应格式是什么。
Just remember to document it, so whoever writes client code will know what to expect.只需记住记录它,这样编写客户端代码的人就会知道会发生什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.