我有一個場景,我想在 Golang 中編組結構時跳過 json 標記。那可能嗎?如果是這樣,我怎樣才能做到這一點?
例如我得到這個json:
{"Employee":{"Interface":{"Name":"xyz", "Address":"abc"}}}
但我希望 json 是:
{"Employee":{"Name":"xyz", "Address":"abc"}}
uj5u.com熱心網友回復:
您可以使用匿名結構
type Employee struct {
Interface Interface
}
type Interface struct {
Name string
Address string
}
func main() {
a := Employee{Interface: Interface{Name: "xyz", Address: "abc"}}
b := struct {
Employee Interface
}{
Employee: a.Interface,
}
jsonResult, _ := json.Marshal(b)
fmt.Println(string(jsonResult)) // {"Employee":{"Name":"xyz","Address":"abc"}}
}
uj5u.com熱心網友回復:
如果Interface欄位的型別不是實際的介面而是結構型別,那么您可以嵌入該欄位,這將提升嵌入結構的欄位Employee并將其編組到 JSON 中將獲得您想要的輸出。
type Employee struct {
Interface // embedded field
}
type Interface struct {
Name string
Address string
}
func main() {
type Output struct{ Employee Employee }
e := Employee{Interface: Interface{Name: "xyz", Address: "abc"}}
out, err := json.Marshal(Output{e})
if err != nil {
panic(err)
}
fmt.Println(string(out))
}
https://play.golang.org/p/s5SFfDzVwPN
如果Interface欄位的型別是實際的介面型別,那么嵌入將無濟于事,相反,您可以讓該Employee型別實作json.Marshaler介面并自定義生成的 JSON。
例如,您可以執行以下操作:
type Employee struct {
Interface Interface `json:"-"`
}
func (e Employee) MarshalJSON() ([]byte, error) {
type E Employee
obj1, err := json.Marshal(E(e))
if err != nil {
return nil, err
}
obj2, err := json.Marshal(e.Interface)
if err != nil {
return nil, err
}
// join the two objects by dropping '}' from obj1 and
// dropping '{' from obj2 and then appending obj2 to obj1
//
// NOTE: if the Interface field was nil, or it contained a type
// other than a struct or a map or a pointer to those, then this
// will produce invalid JSON and marshal will fail with an error.
// If you expect those cases to occur in your program you should
// add some logic here to handle them.
return append(obj1[:len(obj1)-1], obj2[1:]...), nil
}
https://play.golang.org/p/XsWZfDSiFRI
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/358747.html
下一篇:將IEnumerable<Ienumerable<T>>轉換為Dictionary<key,IEnumerable<T>>
