ds3422222222 2014-01-06 06:03
浏览 47
已采纳

json.Unmarshal似乎并不注意struct标记

I have a JSON object that looks like this:

{"API version":"1.2.3"}

And I want to convert it to an object it using the json.Unmarshal() function in go. According to this blog post:

How does Unmarshal identify the fields in which to store the decoded data? For a given JSON key "Foo", Unmarshal will look through the destination struct's fields to find (in order of preference):

  • An exported field with a tag of "Foo" (see the Go spec for more on struct tags),
  • An exported field named "Foo", or
  • An exported field named "FOO" or "FoO" or some other case-insensitive match of "Foo".

This is confirmed by the unmarshal documentation.

Since "API version" has a space in it, which is not a valid go identifier, I used a tag on the field:

type ApiVersion struct {
 Api_version string "API version"
}

And I try to unmarshal it like so:

func GetVersion() (ver ApiVersion, err error) {

 // Snip code that gets the JSON

 log.Println("Json:",string(data))
 err = json.Unmarshal(data,&ver)
 log.Println("Unmarshalled:",ver);
}

The output is:

2014/01/06 16:47:38 Json: {"API version":"1.2.3"}
2014/01/06 16:47:38 Unmarshalled: {}

As you can see, the JSON isn't being marshalled into ver. What am I missing?

  • 写回答

1条回答 默认 最新

  • douzhuo3233 2014-01-06 06:12
    关注

    The encoding/json module requires that the struct tags be namespaced. So you instead want something like:

    type ApiVersion struct {
        Api_version string `json:"API version"`
    }
    

    This is done so that the json struct tags can co-exist with tags from other libraries (such as the XML encoder).

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

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向