简体   繁体   English

Golang/gin 从 gin.Context 解析 JSON

[英]Golang/gin parse JSON from gin.Context

I learned from the gin doc that you can bind json to a struct like我从 gin doc 中了解到,您可以将 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()

    // 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.您始终必须构建一个结构来绑定 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.但是如果有一个非常复杂的JSON数据,我只需要获取其中的一部分,创建一个复杂的struct是一个很大的负担。 Can avoid id and parse it directly?可以避免id直接解析吗?

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.您不需要为 JSON 响应中存在的所有字段创建结构,只需为您感兴趣的字段创建结构。解组时,响应中存在的任何其他字段都将被忽略。

You can also unmarshal to a generic map[string]interface{} but this is only really useful for truly dynamic data.您也可以解组为通用map[string]interface{}但这仅对真正的动态数据真正有用。 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.如果您提前知道响应的格式,您几乎总是最好创建一个自定义结构来获得类型安全并避免在访问地图时进行持续的 nil 检查。 Additionally, a targeted struct avoids storing unnecessary values when JSON in unmarshalled.此外,当 JSON 未编组时,目标结构可避免存储不必要的值。

You can use the JSON to Go tool to help quickly create a struct definition from a JSON response.您可以使用JSON to Go工具帮助从 JSON 响应快速创建结构定义。 You could then easily strip out all the fields you don't need.然后,您可以轻松删除所有不需要的字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM