Home > Backend Development > Golang > How to Unmarshal a JSON Object into a Struct with a Map of Slices?

How to Unmarshal a JSON Object into a Struct with a Map of Slices?

Patricia Arquette
Release: 2024-10-31 16:39:29
Original
995 people have browsed it

How to Unmarshal a JSON Object into a Struct with a Map of Slices?

Custom Unmarshaling a Struct into a Map of Slices

Problem

Custom unmarshaling is required to decode JSON into a struct with a map of slices. Using the default behavior, the map remains empty.

Solution

Using a Custom Unmarshaler:

  1. Implement the json.Unmarshaler interface for the target struct.
  2. In the UnmarshalJSON method:

    • Unmarshal the keys and values of the JSON object as raw, non-decoded JSON.
    • Extract the Last field from the raw JSON value, if it exists.
    • Convert the raw values into a map of slices and assign it to the Pair field.

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>
Copy after login

Alternative solution by adjusting the struct:

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template