1 回答

TA貢獻(xiàn)1794條經(jīng)驗(yàn) 獲得超7個(gè)贊
您可以實(shí)施自定義json.Unmarshaler
.
type Item struct {
Id string `json:"id"`
Name string `json:"name"`
Products ProductList `json:"products"`
}
// Use []*Product if you intend to modify
// the individual elements in the slice.
// Use []Product if the elements are read-only.
type ProductList []*Product
// Implememt the json.Unmarshaler interface.
// This will cause the encoding/json decoder to
// invoke the UnmarshalJSON method, instead of
// performing the default decoding, whenever it
// encounters a ProductList instance.
func (ls *ProductList) UnmarshalJSON(data []byte) error {
// first, do a normal unmarshal
pp := []*Product{}
if err := json.Unmarshal(data, &pp); err != nil {
return err
}
// next, append only the non-nil values
for _, p := range pp {
if p != nil {
*ls = append(*ls, p)
}
}
// done
return nil
}
[]*Variant{}使用 Go1.18及更高版本,您不必為其他[]*Shipping{}類型實(shí)現(xiàn)自定義解組。相反,您可以使用帶有元素類型參數(shù)的切片類型。
type SkipNullList[T any] []*T
func (ls *SkipNullList[T]) UnmarshalJSON(data []byte) error {
pp := []*T{}
if err := json.Unmarshal(data, &pp); err != nil {
return err
}
for _, p := range pp {
if p != nil {
*ls = append(*ls, p)
}
}
return nil
}
type Item struct {
Id string `json:"id"`
Name string `json:"name"`
Products SkipNullList[Product] `json:"products"`
}
type Product struct {
// ...
Variants SkipNullList[Variant] `json:"variants"`
}
type Variant struct {
// ...
Shippings SkipNullList[Shipping] `json:"shippings"`
}
https://go.dev/play/p/az_9Mb_RBKX
- 1 回答
- 0 關(guān)注
- 95 瀏覽
添加回答
舉報(bào)