GoLang JSON Marshal omitempty对于非简单类型是否可以避免使用指针?

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

GoLang JSON Marshal omitempty with non-simple types - possible to avoid pointers?

问题

下面是解释的代码。我能够使非简单类型的omitempty与指针类型一起工作,这是唯一的方法。

是否有不使用指针的替代解决方案?

不工作的代码:

  1. type Foo struct {
  2. Bar Bar `json:"bar,omitempty"`
  3. }
  4. type Bar struct {
  5. Baz string `json:"baz"`
  6. }
  7. func main() {
  8. foo := Foo{}
  9. jsonBytes, _ := json.Marshal(foo)
  10. fmt.Printf("%s\n", jsonBytes)
  11. }

输出:{"bar":{"baz":""}}

工作的代码,但不是我想要的:

  1. type Foo struct {
  2. Bar *Bar `json:"bar,omitempty"`
  3. }
  4. type Bar struct {
  5. Baz string `json:"baz"`
  6. }
  7. func main() {
  8. foo := Foo{}
  9. jsonBytes, _ := json.Marshal(foo)
  10. fmt.Printf("%s\n", jsonBytes)
  11. }

输出:{}

英文:

Code below is the explanation. The only way I can get omitempty to work with non-simple types is to make that type a pointer.

Is there an alternative solution to this by not using pointers?

CODE NOT WORKING:

  1. type Foo struct {
  2. Bar Bar `json:"bar,omitempty"`
  3. }
  4. type Bar struct {
  5. Baz string `json:"baz"`
  6. }
  7. func main() {
  8. foo := Foo{}
  9. jsonBytes, _ := json.Marshal(foo)
  10. fmt.Printf("%s\n", jsonBytes)
  11. }

OUTPUT: {"bar":{"baz":""}}

CODE WORKING, BUT NOT WHAT I WANT:

  1. type Foo struct {
  2. Bar *Bar `json:"bar,omitempty"`
  3. }
  4. type Bar struct {
  5. Baz string `json:"baz"`
  6. }
  7. func main() {
  8. foo := Foo{}
  9. jsonBytes, _ := json.Marshal(foo)
  10. fmt.Printf("%s\n", jsonBytes)
  11. }

OUTPUT: {}

答案1

得分: 1

有没有不使用指针的替代解决方案?

没有。

英文:

> Is there an alternative solution to this by not using pointers?

No.

huangapple
  • 本文由 发表于 2017年6月22日 16:00:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/44693552.html
匿名

发表评论

匿名网友

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

确定