JSON Golang 的 GIN 中的响应作为乱序数据返回
JSON response in Golang’s GIN returning as scrambled data
我有一个结构数组,它是根据我从数据库收集的数据创建的。
为简单起见,假设这是结构:
type Person struct {
ID int `db:"id, json:"id"`
}
type PessoalController struct{}
func (ctrl PessoalController) GetPessoal(c *gin.Context) {
q := "select id from rh"
rows, err := db.GetDB().Query(q)
if err != nil {
log.Fatal(err)
}
defer rows.Close()
var pessoas []Pessoal
var id
for rows.Next() {
err := rows.Scan(&id)
if err != nil {
log.Fatal(err)
}
pessoas = append(pessoas, Pessoal{ ID: id,})
JsonPessoal, errr := json.Marshal(pessoas)
if errr != nil {
log.Fatal(err)
}
c.JSON(200, pessoas)
if err != nil {
return
}
return
}
当我打印它时,我确实得到了我预期的 JSON。
但是当我发送响应时,我得到了看起来很原始的数据,比如“W3siWQiQjlyNDYslNpYx...”
不知道如何进行。
编辑:最小、完整且可验证的示例。
c.JSON
正在序列化为 JSON,因此您应该这样做:
c.JSON(200, pessoas)
你的代码回答了问题本身。看看它并阅读我在代码中的注释。
jsonPessoal, errr := json.Marshal(pessoas)
if errr != nil {
log.Fatal(err)
}
fmt.Fprintf(os.Stdout, "%s", jsonPessoal) // still fine here .
// it is fine because you are formating []byte into string using fmt and
// printing it on console. `%s` makes sures that it echos as string.
c.JSON(200, jsonPessoal ) // jsonPessoal is still a []byte !!
if err != nil {
return
}
使用 gin 回显 json 字符串的正确方法是
c.JSON(http.StatusOK, gin.H{
"code" : http.StatusOK,
"message": string(jsonPessoal),// cast it to string before showing
})
我有一个结构数组,它是根据我从数据库收集的数据创建的。
为简单起见,假设这是结构:
type Person struct {
ID int `db:"id, json:"id"`
}
type PessoalController struct{}
func (ctrl PessoalController) GetPessoal(c *gin.Context) {
q := "select id from rh"
rows, err := db.GetDB().Query(q)
if err != nil {
log.Fatal(err)
}
defer rows.Close()
var pessoas []Pessoal
var id
for rows.Next() {
err := rows.Scan(&id)
if err != nil {
log.Fatal(err)
}
pessoas = append(pessoas, Pessoal{ ID: id,})
JsonPessoal, errr := json.Marshal(pessoas)
if errr != nil {
log.Fatal(err)
}
c.JSON(200, pessoas)
if err != nil {
return
}
return
}
当我打印它时,我确实得到了我预期的 JSON。 但是当我发送响应时,我得到了看起来很原始的数据,比如“W3siWQiQjlyNDYslNpYx...”
不知道如何进行。
编辑:最小、完整且可验证的示例。
c.JSON
正在序列化为 JSON,因此您应该这样做:
c.JSON(200, pessoas)
你的代码回答了问题本身。看看它并阅读我在代码中的注释。
jsonPessoal, errr := json.Marshal(pessoas)
if errr != nil {
log.Fatal(err)
}
fmt.Fprintf(os.Stdout, "%s", jsonPessoal) // still fine here .
// it is fine because you are formating []byte into string using fmt and
// printing it on console. `%s` makes sures that it echos as string.
c.JSON(200, jsonPessoal ) // jsonPessoal is still a []byte !!
if err != nil {
return
}
使用 gin 回显 json 字符串的正确方法是
c.JSON(http.StatusOK, gin.H{
"code" : http.StatusOK,
"message": string(jsonPessoal),// cast it to string before showing
})