Home  >  Article  >  Backend Development  >  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 Dynam

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 Dynam

Susan Sarandon
Susan SarandonOriginal
2024-10-25 11:02:02565browse

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

Custom Unmarshaling of Struct into Map of Slices

Problem Description

Understanding JSON unmarshaling can be challenging. This article explores an issue encountered while unmarshaling a map in Go using the following code snippet:

<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>

Upon running the code, the Pair map remains empty, despite the Last field being unmarshaled correctly.

Solution

Option 1: Adjust Struct Definition

The simplest solution for the provided JSON example is to eliminate the map and align the struct definition with the JSON structure:

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

Option 2: Implement Custom Unmarshaler

If the map keys are dynamic and cannot be hardcoded in the field tags, a custom implementation of the json.Unmarshaler interface is necessary. This can be achieved by implementing the UnmarshalJSON method in the OHLC_RESS struct:

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

The UnmarshalJSON implementation decodes the JSON keys and values separately, treating the "last" element differently from the rest. The remaining elements are unmarshaled into the Pair map.

The above is the detailed content of 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 Dynam. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn