英文:
Go Gin Bind JSON issue
问题
奇怪的是,我的代码中的HTTP POST/GET请求返回的是空的JSON(对于GET请求)或添加了空的结构体(对于POST请求)。
以下是代码片段:
package main
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
)
type employee struct {
id int64 `json:"id" binding:"required"`
}
var all_employee = []employee{
{id: 1},
}
func getEmployees(context *gin.Context) {
context.IndentedJSON(http.StatusOK, all_employee)
return
}
func main() {
router := gin.Default()
router.GET("/allemployees", getEmployees)
}
以下是curl命令的输出:
> curl http://localhost:9099/allemployees
> [
> {}
> ]
希望这能帮到你!
英文:
Strangely http POST/GET request in my code is returning empty JSON (for GET) or adding empty struct ( for POST)
Here is snip of code
package main
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
)
type employee struct {
id int64 `json:"id" binding:"required"`
}
var all_employee = []employee{
{id: 1},
}
func getEmployees(context *gin.Context) {
context.IndentedJSON(http.StatusOK, all_employee)
return
}
func main() {
router := gin.Default()
router.GET("/allemployees", getEmployees)
}
Here is curl output
> curl http://localhost:9099/allemployees
> [
> {}
>]
答案1
得分: 1
这是发生的原因,因为字段"id"没有被导出。
要将JSON解组为结构的字段,该字段需要被导出。
将您的模型更改为:
type employee struct {
Id int64 `json:"id" binding:"required"`
}
应该可以解决这个问题。
注意:
id != Id
这篇帖子有更多详细信息:
https://stackoverflow.com/questions/11126793/json-and-dealing-with-unexported-fields
英文:
That is happening because the field "id" is not exported.
To unmarshal a json to a field of a structure the field need to be exported.
Changing your model to:
type employee struct {
Id int64 `json:"id" binding:"required"`
}
Should fix the problem.
OBS:
id != Id
This post have more details about it:
https://stackoverflow.com/questions/11126793/json-and-dealing-with-unexported-fields
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论