[英]How to Unmarshall/Marshall JSON in Go with Tags?
JSON对象:
{
"foo_bar": "content"
}
编码:
type PrettyStruct struct {
Foo string `json: "foo_bar"`
}
func whatever(r *http.Request) {
var req PrettyStruct
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
// ...
}
log.Println(req)
}
这简单地输出:
{}
Go在解码JSON对象时没有考虑我的标签,因此不会将任何数据编组到struct中,并且每个字段都保持零值。
如果在JSON对象中将该字段称为“ foo”或“ Foo”,则一切正常。
我尝试了简单的标签"foo_bar"
以及以下变体`json: foo_bar`
和"json: foo_bar"
。
我在做什么错了吗?
这很愚蠢..但是冒号和"foo_bar"
之间的空间就是问题所在。 尝试这个:
type PrettyStruct struct {
Foo string `json:"foo_bar"`
// ^^^ no space here
}
在操场上的工作示例: http : //play.golang.org/p/dEc_c0UAOC
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.