我知道这可能是一个常见的问题,但请恕我直言...
我有一个 struct ,其中一个字段类型与另一个 struct 的字段类型相同:
type Developer struct {
Name string `json:"name,omitempty"`
ProjectRef *Ref `json:"project,omitempty"`
}
type Ref struct {
ID string `json:"id,omitempty"`
}
In my implementation I cannot guarantee if there is or isn't going to be a ProjectRef for a Developer. If I create a Ref with a null ID, i.e. an empty string, then this field is omitted from the Ref, however, even though my Ref has no fields at this point, why is it not omitted from being empty?
我想克服这个问题的一种方法是使用一堆条件语句,但我不想让自己这么做,因为我有很多情况下需要这种功能.
完整演示代码:
package main
import (
"encoding/json"
"fmt"
)
type Developer struct {
Name string `json:"name,omitempty"`
ProjectRef *Ref `json:"project,omitempty"`
}
type Ref struct {
ID string `json:"id,omitempty"`
}
func main() {
developer := &Developer{
Name: "Charlie",
ProjectRef: &Ref{ID: ""},
}
jsonBytes, err := json.Marshal(developer)
if err != nil {
panic(err)
}
fmt.Println(string(jsonBytes))
// {"name":"Charlie","project":{}}
}
链接到操场:https://go.dev/play/p/D2edbrACXY2
Thank you in advance