编码/解码json时缺少一个字段

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

encoding/json unmarshal missing a field

问题

以下代码解析了“Id”,但没有解析“Hostname”。为什么?我已经盯着它看了很长时间,如果是拼写错误,我知道我永远也不会发现它。请帮忙。 (http://play.golang.org/p/DIRa2MvvAV)

package main

import (
    "encoding/json"
    "fmt"
)

type jsonStatus struct {
    Hostname string `json:host`
    Id       string `json:id`
}

func main() {
    msg := []byte(`{"host":"Host","id":"Identifier"}`)

    status := new(jsonStatus)

    err := json.Unmarshal(msg, &status)
    if err != nil {
        fmt.Println("Unmarshall err", err)
    }
    fmt.Printf("Got status: %#v\n", status)
}

我得到的输出是

Got status: &main.jsonStatus{Hostname:"", Id:"Identifier"}

我期望的输出是

Got status: &main.jsonStatus{Hostname:"Host", Id:"Identifier"}
英文:

The following code unmarshal's the "Id", but not the "Hostname". Why? I've been staring at it for long enough now that if it's a typo I know I'll never spot it. Help please. (http://play.golang.org/p/DIRa2MvvAV)

package main

import (
	"encoding/json"
	"fmt"
)

type jsonStatus struct {
	Hostname string `json:host`
	Id       string `json:id`
}

func main() {
	msg := []byte(`{"host":"Host","id":"Identifier"}`)

	status := new(jsonStatus)

	err := json.Unmarshal(msg, &status)
	if err != nil {
		fmt.Println("Unmarshall err", err)
	}
	fmt.Printf("Got status: %#v\n", status)
}

The output I get is

Got status: &main.jsonStatus{Hostname:"", Id:"Identifier"}

where I expect

Got status: &main.jsonStatus{Hostname:"Host", Id:"Identifier"}

答案1

得分: 8

你的字段标签是错误的。它们需要在替代名称周围加上引号。

type jsonStatus struct {
    //--------------------v----v
    Hostname string `json:"host"`
    Id       string `json:"id"`
}

从技术上讲,你根本不需要为Id字段添加标签。这就是为什么该字段起作用的原因。

DEMO: http://play.golang.org/p/tiop27jNJe

英文:

Your field tags are wrong. They need quotes around the alternate name.

type jsonStatus struct {
    //--------------------v----v
    Hostname string `json:"host"`
    Id       string `json:"id"`
}

Technically, you don't need a tag for the Id field at all. That's why that field was working.

DEMO: http://play.golang.org/p/tiop27jNJe

huangapple
  • 本文由 发表于 2013年4月16日 01:45:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/16021487.html
匿名

发表评论

匿名网友

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

确定