在结构体中忽略一个对象时,它是`nil`而不是一个空数组。

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

Ignoring an object in struct is nil and not when it's an empty array

问题

当对象为nil时,只使用omitempty而不是当它是一个空数组时,这是可能的吗?

我希望JSON编组器在对象为nil时不显示值,但在值为空列表时显示object: []

objects: nil

{
  ...
}
objects: make([]*Object, 0)

{
  ...
  "objects": []
}
英文:

Is it possible to only use omitempty when an object is nil and not when it's an empty array?

I would like for the JSON marshaller to not display the value when an object is nil, but show object: [] when the value is an empty list.

objects: nil

{
  ...
}
objects: make([]*Object, 0)

{
  ...
  "objects": []
}

答案1

得分: 2

你需要为你的结构体创建自定义的json Marshal/Unmarshal函数,类似于以下代码:

// Hello
type Hello struct {
	World []interface{} `json:"world,omitempty"`
}

// MarshalJSON()
func (h *Hello) MarshalJSON() ([]byte, error) {
	var hello = &struct {
		World []interface{} `json:"world"`
	}{
		World: h.World,
	}
	return json.Marshal(hello)
}

// UnmarshalJSON()
func (h *Hello) UnmarshalJSON(b []byte) error {
	var hello = &struct {
		World []interface{} `json:"world"`
	}{
		World: h.World,
	}

	return json.Unmarshal(b, &hello)
}

输出结果:

{"world":[]}

运行上述示例:https://goplay.tools/snippet/J_iKIJ9ZMhT

英文:

You will need to create a custom json Marshal/Unmarshal functions for your struct. something like:

// Hello
type Hello struct {
	World []interface{} `json:"world,omitempty"`
}

// MarshalJSON()
func (h *Hello) MarshalJSON() ([]byte, error) {
	var hello = &struct {
		World []interface{} `json:"world"`
	}{
		World: h.World,
	}
	return json.Marshal(hello)
}

// UnmarshalJSON()
func (h *Hello) UnmarshalJSON(b []byte) error {
	var hello = &struct {
		World []interface{} `json:"world"`
	}{
		World: h.World,
	}

	return json.Unmarshal(b, &hello)
}

Output:

{"world":[]}

Run above example: https://goplay.tools/snippet/J_iKIJ9ZMhT

答案2

得分: 0

t := []string{}
json, _ := json.Marshal(struct {
	Data *[]string `json:"data,omitempty"`
}{Data: &t})
fmt.Println(string(json)) // 输出: {"data":[]}

https://go.dev/play/p/ZPI39ioU-p5

英文:
	t := []string{}
	json, _ := json.Marshal(struct {
		Data *[]string `json:"data,omitempty"`
	}{Data: &t})
	fmt.Println(string(json)) // Output: {"data":[]}

https://go.dev/play/p/ZPI39ioU-p5

huangapple
  • 本文由 发表于 2022年5月15日 07:03:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/72244429.html
匿名

发表评论

匿名网友

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

确定