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

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

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

问题

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

{
    "first_name": "John",
    "last_name": "Doe"
}

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

package main

import (
    "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时,它总是只打印一个换行符。我做错了什么?

英文:

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

{
	"first_name": "John",
	"last_name": "Doe"
}

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

package main

import (
	"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)
}

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:

确定