Home  >  Article  >  Backend Development  >  How to Unmarshal a JSON Map into a Go Struct with Custom Handling?

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

Patricia Arquette
Patricia ArquetteOriginal
2024-10-26 06:21:30135browse

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

Custom Unmarshaling a Struct into a Map of Slices

In Go, unmarshaling involves converting JSON data into a Go data structure. While the basic principles of unmarshaling are straightforward, specific scenarios, like populating a map, might need custom handling.

Issue: Populating a Map in Unmarshaling

A common problem encountered is trying to unmarshal a map into a Go struct. Consider the following example:

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

On attempting to unmarshal JSON data with the above struct, the Last field is populated successfully, but the Pair map remains empty.

Solution: Custom Unmarshaling for the Struct

The default unmarshaling process in Go uses field names and tags to match JSON keys. However, in this case, the Pair map needs custom handling as its key names are not known in advance. To achieve this, implement the json.Unmarshaler interface for the OHLC_RESS struct:

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

This custom unmarshaling function separates the decoding process into steps. It first decodes the object's keys, then handles the "last" element separately, and finally, it decodes the remaining elements into the Pair map. This approach grants control over the decoding process and allows for custom handling of specific fields like the Pair map.

The above is the detailed content of How to Unmarshal a JSON Map into a Go Struct with Custom Handling?. 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