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

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

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?