dqtok88424 2016-04-22 20:14
浏览 55
已采纳

为什么我无法使用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?

  • 写回答

1条回答 默认 最新

  • doulingna9420 2016-04-22 21:41
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改
  • ¥15 Windows 系统cmd后提示“加载用户设置时遇到错误”
  • ¥50 vue router 动态路由问题
  • ¥15 关于#.net#的问题:End Function
  • ¥15 无法import pycausal
  • ¥15 weditor无法连接模拟器Local server not started, start with?
  • ¥20 6-3 String类定义
  • ¥15 嵌入式--定时器使用