英文:
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":[]}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论