我的服务器上有一个非常简单的 JSON 文件,只是{ "first_name": "John", "last_name": "Doe"}然后我写了一个 golang 脚本来打印出名字:package mainimport ( "fmt" "net/http" "encoding/json") type Person struct { FirstName string `json: "first_name"` LastName string `json: "last_name"`}func main() { url := "http://myserver.com/test.json" res, err := http.Get(url) if err != nil { fmt.Printf("%s", err) } defer res.Body.Close() var person Person dec := json.NewDecoder(res.Body).Decode(&person) if dec != nil { fmt.Printf("%s", dec) } fmt.Println(person.FirstName)}但是如果我输入go run test.go它似乎总是只打印一个换行符。我究竟做错了什么?
1 回答

慕尼黑8549860
TA贡献1818条经验 获得超11个赞
您的代码正在您的 json 中搜索FirstName
和LastName
键。如果你想让结构标签生效,你需要去掉冒号和引号之间的空格。json:"first_name"
https://golang.org/pkg/reflect/#StructTag
- 1 回答
- 0 关注
- 201 浏览
添加回答
举报
0/150
提交
取消