亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將 JSON 數組解組為指針切片時跳過空值

將 JSON 數組解組為指針切片時跳過空值

Go
千萬里不及你 2022-12-19 10:59:49
我有以下結構:type Item struct {    Id       string     `json:"id"`    Name     string     `json:"name"`    Products []*Product `json:"products"`}func (i *Item) Transform(input []byte) error {    return json.Unmarshal(input, i)}Products我必須對它的成員和它的嵌套成員執行多項操作,例如[]*Variant{}or[]*Shipping{}等。因為結構中的大部分切片Item都是指針切片,所以我處理這些數據的代碼如下所示:for _, product := range i.Products {    if product == nil {        continue    }        for _, variant := range product.Variants {        if variant == nil {            continue        }                for _, shipping := range shippings {            if shipping == nil {                continue            }                  // and so on...        }    }}有什么方法可以模仿指針切片中的值嗎omitempty?nil下面的例子。JSON 輸入:{    "products": [        null,        {},        null    ]}輸出,相當于:input := Item{    Products: []Product{ {} }, // without nulls}我嘗試使用omitemptyon[]*Property但它不起作用。我還嘗試使用非指針值,但隨后 Go 將每個 null 初始化為默認結構值。
查看完整描述

1 回答

?
慕田峪9158850

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


查看完整回答
反對 回復 2022-12-19
  • 1 回答
  • 0 關注
  • 98 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號