java - Spring NumberFormatException : Failed to convert value of type 'java.lang.String' to required type 'java. lang.Long

标签 java spring rest spring-mvc

我不确定我是否遗漏了一些非常基本的东西,但这是我想做的。

我想对这个地址进行 rest API 调用:

https://localhost:8080/fetchlocation?lat=-26.2041028&lng=28.0473051&radius=500

我的休息方式是:

public void fetchlocation(@RequestParam Long lat, @RequestParam Long lng, @RequestParam int radius){ //fetches location}

我收到这个错误:

"timestamp": 1442751996949, "status": 400, "error": "Bad Request", "exception": "org.springframework.beans.TypeMismatchException",
"message": "Failed to convert value of type 'java.lang.String' to required type 'java.lang.Long'; nested exception is java.lang.NumberFormatException: For input string: \"-26.2041028\"",
"path": "/fetchlocation"

我猜这是因为当我进行 GET 调用时,rest API 将坐标作为字符串而不是 Long 接收。如何确保其余 API 在调用时获取 Longs 而不是 String 值?

当我更改其余 API 方法以将字符串作为参数时,我可以轻松地使该方法工作,但对于类型检查,我更愿意使用 Longs。

public void fetchlocation(@RequestParam String lat, @RequestParam String lng, @RequestParam String radius){ //fetches location}

最佳答案

您尝试转换为 java.lang.Long 的数字是 -26.2041028

您的号码包含一个 .(十进制)。这对于 Long 是不允许的。您需要使用 java.lang.Double

并且还可以在您的数字后面加上 L 表示 LongD 表示 Double 以进行静态初始化。尽管不是必需的,但它使代码更具可读性。

例如,-26.2041028D 用于Double

关于java - Spring NumberFormatException : Failed to convert value of type 'java.lang.String' to required type 'java. lang.Long,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32679451/

相关文章:

c++ - 在 Casablanca 中设置基本 HTTP 身份验证

c# - 在 UWP 中接收来自 HttpClient 的响应时编码错误

java - 如何在 Android 谷歌地图中制作自定义 Tiles

java - 获取已加载到 webview 中的 URL 的 HttpResponse

java - Spring Boot 设置 MongoDB 存储库

java - HTTP 状态 400 - 客户端发送的请求在语法上不正确。 - 在使用 Hibernate 的 Spring MVC Web 应用程序中

c# - azure 函数中的 HTTP 补丁

java - 配置JmsListener执行顺序

java - 将字符串输出到系统输出的最快方法是什么?

java - Spring MongoDB 流内存泄漏?