Go Gin绑定JSON问题

huangapple go评论82阅读模式
英文:

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

huangapple
  • 本文由 发表于 2022年8月3日 14:48:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/73217380.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定