【问题标题】:How do I lowercase a nested struct name when using json.marshal?使用 json.marshal 时如何小写嵌套的结构名称?
【发布时间】:2021-12-21 22:20:05
【问题描述】:

我正在公开一个带有一些数据的 REST 端点。这是一个结构,比如说:

type status struct {
    Config struct {
        Allow   bool `json:"allow"`
        Expired bool `json:"expired"`
    }
    Database struct {
        Healthy          bool   `json:"healthy"`
        WaitCount        int64  `json:"wait_count"`
    }
}

我使用 json 标记来表示调用端点时结构字段的外观。使用上述内容,我得到以下有效负载作为响应:

{
    "Config": {
        "allow": false,
        "expired": false,
    },
    "Database": {
        "healthy": true,
        "wait_count": 1,
    },
}

我希望 ConfigDatabase 小写,意思是 configdatabase。但是,将它们更改为 Go 代码中的内容意味着 "encoding/json" 包无法“看到”它们,因为它们没有导出到包范围之外。

如何在 json 响应负载中小写嵌套结构?

【问题讨论】:

    标签: json go


    【解决方案1】:

    嵌套结构是包含结构中的一个字段。像添加其他字段一样添加字段标签:

    type status struct {
        Config struct {
            Allow   bool `json:"allow"`
            Expired bool `json:"expired"`
        } `json:"config"` // <-- add tag here ...
        Database struct {
            Healthy          bool   `json:"healthy"`
            WaitCount        int64  `json:"wait_count"`
        } `json:"database"` // <-- ... and here
    }
    

    【讨论】:

      猜你喜欢
      • 2013-06-22
      • 2021-10-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-13
      • 2020-09-27
      • 2019-05-01
      • 1970-01-01
      • 2021-05-26
      相关资源
      最近更新 更多