首頁  >  文章  >  後端開發  >  如何使用自訂處理將 JSON 映射解組為 Go 結構?

如何使用自訂處理將 JSON 映射解組為 Go 結構?

Patricia Arquette
Patricia Arquette原創
2024-10-26 06:21:30135瀏覽

How to Unmarshal a JSON Map into a Go Struct with Custom Handling?

自訂將結構解組為切片映射

在 Go 中,解組涉及將 JSON 資料轉換為 Go 資料結構。雖然解組的基本原理很簡單,但特定場景(例如填充地圖)可能需要自訂處理。

問題:在解組中填入地圖

遇到的常見問題是嘗試解組映射到 Go 結構體。考慮以下範例:

<code class="go">type OHLC_RESS struct {
    Pair map[string][]Candles
    Last int64 `json:"last"`
}

// Candles represents individual candlesticks within the map.
type Candles struct {
    // ... Time, Open, High, Low, Close, VWAP, Volume, Count fields omitted
}</code>

嘗試使用上述結構解組 JSON 資料時,Last 欄位已成功填充,但 Pair 對應仍為空。

解決方案:自訂解組Struct

Go 中預設的解組過程使用欄位名稱和標籤來匹配 JSON 鍵。但是,在這種情況下,Pair 映射需要自訂處理,因為其鍵名稱事先未知。為此,請為 OHLC_RESS 結構實作 json.Unmarshaler 介面:

<code class="go">func (r *OHLC_RESS) UnmarshalJSON(d []byte) error {
    // Decode only the object's keys and leave values as raw JSON.
    var obj map[string]json.RawMessage
    if err := json.Unmarshal(d, &obj); err != nil {
        return err
    }

    // Decode the "last" element into the Last field.
    if last, ok := obj["last"]; ok {
        if err := json.Unmarshal(last, &r.Last); err != nil {
            return err
        }
        delete(obj, "last")
    }

    // Decode the remaining elements into the Pair map.
    r.Pair = make(map[string][]Candles, len(obj))
    for key, val := range obj {
        cc := []Candles{}
        if err := json.Unmarshal(val, &cc); err != nil {
            return err
        }
        r.Pair[key] = cc
    }

    return nil
}</code>

此自訂解組函數將解碼過程分成多個步驟。它首先解碼物件的鍵,然後單獨處理「最後」元素,最後將剩餘元素解碼到 Pair 映射中。這種方法可以控制解碼過程,並允許自訂處理特定字段,例如配對映射。

以上是如何使用自訂處理將 JSON 映射解組為 Go 結構?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn