Json将结构体映射为空对象。

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

Json marshal map of structs results in empty object

问题

我有一个简单的对象定义:

  1. type Link struct {
  2. Href string `json:"href"`
  3. Title string `json:"href,omitempty"`
  4. }
  5. type Foo struct {
  6. Links map[string]Link `json:"_links"`
  7. }
  8. foo := new(Foo)
  9. foo.Links = make(map[string]Link, 0)
  10. foo.Links["self"] = Link{Href: "/href"}

将其编组为JSON后,我期望得到:

  1. {
  2. "_links": {
  3. "self": {
  4. "href": "/href"
  5. }
  6. }
  7. }

但实际上我得到的是:

  1. {
  2. "_links": {
  3. "self": {}
  4. }
  5. }

有任何想法为什么会这样吗?这里是一个完整的示例:

https://play.golang.org/p/3RA3Mrx3pt

英文:

I have a simple object defined:

  1. type Link struct {
  2. Href string `json:"href"`
  3. Title string `json:"href,omitempty"`
  4. }
  5. type Foo struct {
  6. Links map[string]Link `json:"_links"`
  7. }
  8. foo := new(Foo)
  9. foo.Links = make(map[string]Link, 0)
  10. foo.Links["self"] = Link{Href: "/href"}

After marshalling it to JSON, I'd expect:

  1. {
  2. "_links": {
  3. "self": {
  4. "href": "/href"
  5. }
  6. }
  7. }

But instead I get:

  1. {
  2. "_links": {
  3. "self": {}
  4. }
  5. }

Any idea why? Here's a full example:

https://play.golang.org/p/3RA3Mrx3pt

答案1

得分: 4

你已经两次定义了json:"href"

  1. type Link struct {
  2. Href string `json:"href"`
  3. Title string `json:"href,omitempty"`
  4. }

将第二次更改为json:"title"后,它可以正常工作:https://play.golang.org/p/uEbyqtHYF8。

英文:

You've defined json:"href" twice:

  1. type Link struct {
  2. Href string `json:"href"`
  3. Title string `json:"href,omitempty"`
  4. }

After changing the second to json:"title" it works: https://play.golang.org/p/uEbyqtHYF8.

huangapple
  • 本文由 发表于 2016年1月15日 02:01:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/34796586.html
匿名

发表评论

匿名网友

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

确定