为什么我无法使用golang解码这个JSON?它总是打印一个空字符串。

huangapple go评论130阅读模式
英文:

Why am I not able to decode this JSON with golang? It always prints an empty string

问题

我在我的服务器上有一个非常简单的JSON文件,内容如下:

  1. {
  2. "first_name": "John",
  3. "last_name": "Doe"
  4. }

然后我编写了一个用于打印出名字的Golang脚本:

  1. package main
  2. import (
  3. "fmt"
  4. "net/http"
  5. "encoding/json"
  6. )
  7. type Person struct {
  8. FirstName string `json:"first_name"`
  9. LastName string `json:"last_name"`
  10. }
  11. func main() {
  12. url := "http://myserver.com/test.json"
  13. res, err := http.Get(url)
  14. if err != nil {
  15. fmt.Printf("%s", err)
  16. }
  17. defer res.Body.Close()
  18. var person Person
  19. dec := json.NewDecoder(res.Body).Decode(&person)
  20. if dec != nil {
  21. fmt.Printf("%s", dec)
  22. }
  23. fmt.Println(person.FirstName)
  24. }

但是,当我运行go run test.go时,它总是只打印一个换行符。我做错了什么?

英文:

I have a JSON file on my server that is very simple, just

  1. {
  2. "first_name": "John",
  3. "last_name": "Doe"
  4. }

I then wrote a golang script to print out the first name:

  1. package main
  2. import (
  3. "fmt"
  4. "net/http"
  5. "encoding/json"
  6. )
  7. type Person struct {
  8. FirstName string `json: "first_name"`
  9. LastName string `json: "last_name"`
  10. }
  11. func main() {
  12. url := "http://myserver.com/test.json"
  13. res, err := http.Get(url)
  14. if err != nil {
  15. fmt.Printf("%s", err)
  16. }
  17. defer res.Body.Close()
  18. var person Person
  19. dec := json.NewDecoder(res.Body).Decode(&person)
  20. if dec != nil {
  21. fmt.Printf("%s", dec)
  22. }
  23. fmt.Println(person.FirstName)
  24. }

But if I type go run test.go it always just prints a newline character seemingly.

What am I doing wrong?

答案1

得分: 2

你的代码正在搜索json中的FirstNameLastName键。如果你想让结构标签生效,你需要在冒号和引号之间去掉空格,即json:"first_name"

你可以参考这个链接了解更多关于结构标签的信息:https://golang.org/pkg/reflect/#StructTag

英文:

Your code is searching FirstName and LastName keys in your json. If you want struct tags take effect, you need to remove space between colon and quote. json:"first_name"

https://golang.org/pkg/reflect/#StructTag

huangapple
  • 本文由 发表于 2016年4月23日 04:14:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/36802591.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定