Home > Article > Backend Development > How to Unmarshal a JSON Object into a Struct with a Map of Slices?
Custom unmarshaling is required to decode JSON into a struct with a map of slices. Using the default behavior, the map remains empty.
Using a Custom Unmarshaler:
In the UnmarshalJSON method:
Alternative Solution (Not Using a Map):
If the JSON structure is fixed, the target struct can be adjusted to match the JSON layout without using a map.
Example:
Custom unmarshaling code using the custom UnmarshalJSON method:
<code class="go">func (r *OHLC_RESS) UnmarshalJSON(d []byte) error { // Decode keys and values var obj map[string]json.RawMessage if err := json.Unmarshal(d, &obj); err != nil { return err } // Extract "last" field if last, ok := obj["last"]; ok { if err := json.Unmarshal(last, &r.Last); err != nil { return err } delete(obj, "last") } // Decode and assign Pair field 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>
Alternative solution by adjusting the struct:
<code class="go">type OHLC_RESS struct { Pair []Candles `json:"XXBTZUSD"` Last int64 `json:"last"` }</code>
The above is the detailed content of How to Unmarshal a JSON Object into a Struct with a Map of Slices?. For more information, please follow other related articles on the PHP Chinese website!