英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论