1 回答
TA贡献1794条经验 获得超7个赞
您可以实施自定义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{}类型实现自定义解组。相反,您可以使用带有元素类型参数的切片类型。
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 关注
- 74 浏览
添加回答
举报