How to Unmarshall/Marshall JSON in Go with Tags?

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

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对象时没有考虑我的标签,因此没有将任何内容解组到结构体中,每个字段都保持零值。
如果在JSON对象中,字段被称为"foo"或"Foo",则一切正常工作。

我尝试了简单的标签"foo_bar"和以下变体`json:"foo_bar"`"json:"foo_bar"

对于我做错了什么,有什么想法吗?

英文:

The JSON object:

{  
"foo_bar": "content"  
}

The code:

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)
}

This outputs simply:

{}  

Go isn't considering my tags when decoding the JSON object, so nothing is unmarshalled into the struct and every field stays with the zero-value.
If, in the JSON object, the field was called "foo" or "Foo", everything works normally.

I've tried the simple tag "foo_bar" and the following variations `json: foo_bar` and "json: foo_bar".

Any thoughs on what am I doing wrong?

答案1

得分: 1

这是一个愚蠢的问题..但是冒号和"foo_bar"之间的空格是问题所在。尝试这样做:

type PrettyStruct struct {
    Foo       string  `json:"foo_bar"`
    //                     ^^^ 这里不要有空格
}

在playground上的工作示例:http://play.golang.org/p/dEc_c0UAOC

英文:

It's silly.. but the space between the colon and the "foo_bar" is the problem. Try this:

type PrettyStruct struct {
    Foo       string  `json:"foo_bar"`
    //                     ^^^ no space here
}

Working example on the playground: http://play.golang.org/p/dEc_c0UAOC

huangapple
  • 本文由 发表于 2014年9月19日 08:09:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/25924393.html
匿名

发表评论

匿名网友

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

确定