简体   繁体   中英

JSON response in Golang’s GIN returning as scrambled data

I have array of a struct being created from data I collected from the database.

For simplicity, lets say this is the struct:

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
}

When I print it, I do get the JSON I expected. But when I send the response, I get raw-looking data like “W3siWQiQjlyNDYslNpYx...”

Have no idea how to proceed.

Edit : Minimal, Complete, and Verifiable example.

c.JSON正在序列化为JSON,因此您应该这样做:

c.JSON(200, pessoas)

Your codes ans the question itself. Look at it and read my comments in the code.

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
}

The correct way to echo json string using gin would be

c.JSON(http.StatusOK, gin.H{ 
            "code" : http.StatusOK, 
            "message": string(jsonPessoal),// cast it to string before showing
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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