问题描述

今天使用c.JSON(), 返回前fmt.Println()可以正常输出, 但是c.JSON()一直返回为空.

代码示例

type Msg struct{
	name    string `json:"user"`
	message string
	number  int
}

r.GET("/moreJSON", func(c *gin.Context) {
        // 直接使用结构体定义
        var msg Msg
        msg.name = "Lena"
        msg.message = "hey"
        msg.number = 123
        fmt.Println(msg) // 正常输出msg内容
        c.JSON(http.StatusOK, msg)// 会输出  {} 为空
    })

问题解决与原因

Msg结构体中成员变量需要大写字母开头, 不然小写字母默认为私有变量, 在包内输出时正常, 但是c.JSON()调用JSON/marshal()进行序列化, 属于包外方法, 无法解析到小写字母开头的成员变量.
改成这样就正常了.

type Msg struct{
	Name    string `json:"user"`
	Message string
	Number  int
}
r.GET("/moreJSON", func(c *gin.Context) {
        msg.Name = "Lena"
        msg.Message = "hey"
        msg.Number = 123
        // 会输出  {"user": "Lena", "Message": "hey", "Number": 123}
        c.JSON(http.StatusOK, msg)
    })
GitHub 加速计划 / js / json
51
5
下载
适用于现代 C++ 的 JSON。
最近提交(Master分支:2 天前 )
dff2b475 Adds pre-multiplication overflow detection to catch cases where dimension products would exceed size_t max. The previous check only detected when overflow resulted in exactly 0 or SIZE_MAX, missing other cases. Retains the original post-multiplication check for backward compatibility. Adds tests verifying overflow detection with dimensions (2^32+1)×(2^32), which previously overflowed silently to 2^32. This prevents custom SAX handlers from receiving incorrect array sizes that could lead to buffer overflows. Signed-off-by: Ville Vesilehto <ville@vesilehto.fi> 1 天前
eef76c20 * :white_check_mark: add test for C++20 modules Signed-off-by: Niels Lohmann <mail@nlohmann.me> * :rotating_light: fix warning Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Add missing header (#4763) * :bug: add missing header Signed-off-by: Niels Lohmann <mail@nlohmann.me> * :rotating_light: fix warning Signed-off-by: Niels Lohmann <mail@nlohmann.me> * :rotating_light: fix warning Signed-off-by: Niels Lohmann <mail@nlohmann.me> --------- Signed-off-by: Niels Lohmann <mail@nlohmann.me> --------- Signed-off-by: Niels Lohmann <mail@nlohmann.me> 2 天前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐