Golang/gin从gin.Context解析JSON

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

Golang/gin parse JSON from gin.Context

问题

我从gin文档中了解到,你可以将JSON绑定到一个结构体中,例如:

type Login struct {
    User     string `form:"user" json:"user" binding:"required"`
    Password string `form:"password" json:"password" binding:"required"`
}

func main() {
    router := gin.Default()

    // 绑定JSON的示例({"user": "manu", "password": "123"})
    router.POST("/loginJSON", func(c *gin.Context) {
        var json Login
        if c.BindJSON(&json) == nil {
            if json.User == "manu" && json.Password == "123" {
                c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
            } else {
                c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
            }
        }
    })
}

你总是需要构建一个结构体来绑定JSON数据。

但是,如果有一个非常复杂的JSON数据,我只想获取其中的一部分,创建一个复杂的结构体会很麻烦。是否可以避免创建结构体,直接解析JSON数据呢?

英文:

I learned from the gin doc that you can bind json to a struct like

type Login struct {
	User     string `form:"user" json:"user" binding:"required"`
	Password string `form:"password" json:"password" binding:"required"`
}

func main() {
	router := gin.Default()

	// Example for binding JSON ({"user": "manu", "password": "123"})
	router.POST("/loginJSON", func(c *gin.Context) {
		var json Login
		if c.BindJSON(&json) == nil {
			if json.User == "manu" && json.Password == "123" {
				c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
			} else {
				c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
			}
		}
	})
}

You always have to build a struct to bind JSON.

But if there is a very complex JSON data, I only what to get part of it, to create a complex struct is a big burden. Can avoid id and parse it directly?

答案1

得分: 6

你不需要为 JSON 响应中的所有字段创建一个结构体,只需要创建你感兴趣的字段的结构体即可。当解组时,忽略响应中的其他字段。

你也可以解组到一个通用的 map[string]interface{},但这只对真正动态的数据有用。如果你提前知道响应的格式,最好还是创建一个自定义的结构体,以获得类型安全性,并避免在访问 map 时不断进行 nil 检查。此外,有针对性的结构体在解组 JSON 时避免了存储不必要的值。

你可以使用 JSON to Go 工具,快速从 JSON 响应中创建一个结构体定义。然后,你可以轻松地删除所有不需要的字段。

英文:

You don't need to create a struct for all the fields present in the JSON response, only the fields you are interested in. Any other fields present in the response will be ignored when unmarshaling.

You can also unmarshal to a generic map[string]interface{} but this is only really useful for truly dynamic data. If you know the format of the response ahead of time you will nearly always be best to create a custom struct to get type safety and avoid continual nil checks when accessing the map. Additionally, a targeted struct avoids storing unnecessary values when JSON in unmarshalled.

You can use the JSON to Go tool to help quickly create a struct definition from a JSON response. You could then easily strip out all the fields you don't need.

huangapple
  • 本文由 发表于 2017年8月11日 14:53:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/45628770.html
匿名

发表评论

匿名网友

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

确定