我通过网址发送带有net / http包的Json数据,我想要一些小写的键作为回报,但它不起作用。
在这个问题的例子中,我想要小写的'count'和'data'键。
package main
import (
"encoding/json"
"fmt"
"net/http"
)
type tableau struct {
Count int `json"count"`
Data []People `json"data"`
}
type People struct {
Id int `json"Id"`
Name string `json"Name"`
Age int `json"Age"`
}
func main() {
http.HandleFunc("/people", recupPeople)
fs := http.FileServer(http.Dir("Static"))
http.Handle("/", fs)
http.ListenAndServe(":80", nil)
}
func recupPeople(w http.ResponseWriter, r *http.Request) {
listPeople := &tableau{
Count: 4,
Data: []People{
People{Id: 1, Name: "Laurent", Age: 20},
People{Id: 2, Name: "Laurent", Age: 20},
},
}
peop, _ := json.Marshal(listPeople)
fmt.Println(string(peop))
w.Write(peop)
json.NewEncoder(w).Encode(listPeople)
}
亲切, 劳伦
答案 0 :(得分:6)
你在标签声明中忘记了冒号。由于标签的格式不正确,因此字段名称位于json中。
试试这个:
type tableau struct {
Count int `json:"count"`
Data []People `json:"data"`
}
答案 1 :(得分:3)
尝试在结构代码中添加:
:
type tableau struct {
Count int `json:"count"`
Data []People `json:"data"`
}