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

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

问题描述:

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?

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