首页 > 后端开发 > Golang > 正文

如何使用自定义处理将 JSON 映射解组为 Go 结构?

Patricia Arquette
发布: 2024-10-26 06:21:30
原创
148 人浏览过

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

自定义将结构解组为切片映射

在 Go 中,解组涉及将 JSON 数据转换为 Go 数据结构。虽然解组的基本原理很简单,但特定场景(例如填充地图)可能需要自定义处理。

问题:在解组中填充地图

遇到的常见问题是尝试解组映射到 Go 结构体中。考虑以下示例:

<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>
登录后复制

尝试使用上述结构解组 JSON 数据时,Last 字段已成功填充,但 Pair 映射仍为空。

解决方案:自定义解组Struct

Go 中默认的解组过程使用字段名称和标签来匹配 JSON 键。但是,在这种情况下,Pair 映射需要自定义处理,因为其键名称事先未知。为此,请为 OHLC_RESS 结构实现 json.Unmarshaler 接口:

<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>
登录后复制

此自定义解组函数将解码过程分为多个步骤。它首先解码对象的键,然后单独处理“最后”元素,最后将剩余元素解码到 Pair 映射中。这种方法可以控制解码过程,并允许自定义处理特定字段,例如配对映射。

以上是如何使用自定义处理将 JSON 映射解组为 Go 结构?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!