Home >Backend Development >Golang >How can I custom unmarshal a struct into a map of slices in Go when the JSON keys don\'t match the struct field names?

How can I custom unmarshal a struct into a map of slices in Go when the JSON keys don\'t match the struct field names?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-26 14:00:04824browse

How can I custom unmarshal a struct into a map of slices in Go when the JSON keys don't match the struct field names?

Custom Unmarshaling a Struct into a Map of Slices

When dealing with JSON data, you may encounter scenarios where you need to map specific elements within the JSON object to a field that aligns with your data structure. However, the default JSON unmarshaling mechanism may not always meet these requirements. This is where custom unmarshaling comes into play.

In the example provided, you have a struct OHLC_RESS with a map field Pair expecting slices of Candles as values. However, the initial code fails to populate the Pair map.

Understanding the Issue

The unmarshaling behavior stems from several factors:

  1. JSON object keys do not correspond to struct field names.
  2. The field name Pair does not provide any special meaning to the unmarshaler.
  3. The Last field is unmarshaled because its JSON key (last) matches the field name.

Tailored Unmarshaling Solution

To address these issues, you can leverage the json.Unmarshaler interface by implementing the relevant method within your struct:

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

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

    // Unmarshal 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 solution:

  1. Separates the decoding of the Last field from the remaining object's values.
  2. Creates a map with string keys and []Candles values to store the pairs.
  3. Iterates through the remaining JSON keys and values, unmarshaling each into a slice of Candles and storing it in the Pair map.

By implementing this custom unmarshaling, you gain the flexibility to control how specific JSON elements are mapped to your desired data structure, even when the JSON object's structure does not directly align with it.

The above is the detailed content of How can I custom unmarshal a struct into a map of slices in Go when the JSON keys don\'t match the struct field names?. 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