首頁  >  文章  >  後端開發  >  以下是一些問題格式的標題選項,適合您提供的文章的內容: **直接且以問題為中心:** * **當鍵是動態的時如何解組 Go 中的切片映射

以下是一些問題格式的標題選項,適合您提供的文章的內容: **直接且以問題為中心:** * **當鍵是動態的時如何解組 Go 中的切片映射

Susan Sarandon
Susan Sarandon原創
2024-10-25 11:02:02565瀏覽

Here are a few title options in a question format, catering to the content of your provided article:

**Direct &  Problem-Focused:**

* **How to Unmarshal a Map of Slices in Go When Keys are Dynamic?**
* **Empty Map After Unmarshaling: Why is my Go Struct

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

問題描述

理解 JSON 解組可能具有挑戰性。本文探討了使用以下程式碼片段在 Go 中解組映射時遇到的問題:

<code class="go">import (
    "encoding/json"
    "fmt"
)

type OHLC_RESS struct {
    Pair map[string][]Candles
    Last int64 `json:"last"`
}

type Candles struct {
    // ...
}

func (c *Candles) UnmarshalJSON(d []byte) error {
    // ...
}

func main() {
    // ...
}</code>

運行程式碼後,儘管 Last 欄位已正確解組,但 Pair 映射仍為空。

解決方案

選項1:調整結構體定義

所提供的JSON 範例的最簡單解決方案是消除映射並將結構體定義與JSON 結構對齊:

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

選項2:實現自訂Unmarshaler

如果映射鍵是動態的且無法在字段標籤中硬編碼,則字段標籤中硬編碼,則字段標籤自訂實作json.Unmarshaler介面是必要的。這可以透過在 OHLC_RESS 結構中實作 UnmarshalJSON 方法來實現:

<code class="go">func (r *OHLC_RESS) UnmarshalJSON(d []byte) error {
    // ...
}</code>

UnmarshalJSON 實作分別解碼 JSON 鍵和值,以不同於其他元素的方式處理「最後一個」元素。剩餘元素被解組到 Pair 映射中。

以上是以下是一些問題格式的標題選項,適合您提供的文章的內容: **直接且以問題為中心:** * **當鍵是動態的時如何解組 Go 中的切片映射的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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