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

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

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

问题

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

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

不工作的代码:

type Foo struct {
    Bar Bar `json:"bar,omitempty"`
}

type Bar struct {
    Baz string `json:"baz"`
}

func main() {

    foo := Foo{}

    jsonBytes, _ := json.Marshal(foo)

    fmt.Printf("%s\n", jsonBytes)
}

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

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

type Foo struct {
    Bar *Bar `json:"bar,omitempty"`
}

type Bar struct {
    Baz string `json:"baz"`
}

func main() {

    foo := Foo{}

    jsonBytes, _ := json.Marshal(foo)

    fmt.Printf("%s\n", jsonBytes)
}

输出:{}

英文:

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:

type Foo struct {
	Bar Bar `json:"bar,omitempty"`
}

type Bar struct {
	Baz string `json:"baz"`
}

func main() {

	foo := Foo{}

	jsonBytes, _ := json.Marshal(foo)

	fmt.Printf("%s\n", jsonBytes)
}

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

CODE WORKING, BUT NOT WHAT I WANT:

type Foo struct {
	Bar *Bar `json:"bar,omitempty"`
}

type Bar struct {
	Baz string `json:"baz"`
}

func main() {

	foo := Foo{}

	jsonBytes, _ := json.Marshal(foo)

	fmt.Printf("%s\n", jsonBytes)
}

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:

确定