【问题标题】:How to use mapstructure tag as json tag?如何使用mapstructure标签作为json标签?
【发布时间】:2019-08-21 02:35:03
【问题描述】:

我正在介绍一个来自第三方的包,其中包含 structmapstructure 标签。

我希望这个结构的实例是带有mapstructure指定值的json。我该怎么办?

我可以添加json标签,但是这样做,我修改了包文件,我认为这是一个不好的方式。

type ServiceConfig struct {
    // name of the service
    Name string `mapstructure:"name"`
    // set of endpoint definitions
    Endpoints string `mapstructure:"end_points"`
    // defafult timeout
    Timeout time.Duration `mapstructure:"timeout"`
}

我想得到:

{"name":"sss", "end_points" :"xxx", "timeout" : "120"}

【问题讨论】:

    标签: go tags


    【解决方案1】:

    如果您不想修改包文件,可以创建另一个具有相同字段名称但带有 JSON 标签的结构,然后复制:

    type JSONServiceConfig struct {
        Name      string        `json:"name"`
        Endpoints string        `json:"end_points"`
        Timeout   time.Duration `json:"timeout"`
    }
    

    然后:

    x := JSONServiceConfig(serviceConfig)
    

    【讨论】:

      【解决方案2】:

      如果不修改mapstructure 源,你就无法做你想做的事,如果你想指定选项,比如jsonomitempty,它可能会有点麻烦。但是,您可以简单地为此添加第二个结构标记

      type ServiceConfig struct {
          // name of the service
          Name string `mapstructure:"name" json:"name"`
          // set of endpoint definitions
          Endpoints string `mapstructure:"end_points" json:"end_points"`
          // defafult timeout
          Timeout time.Duration `mapstructure:"timeout" json:"timeout"`
      }
      

      来自reflect的文档

      按照惯例,标签字符串是可选的串联 空格分隔的键:“值”对。每个键都是一个非空字符串 由除空格以外的非控制字符 (U+0020 ' ') 组成, 引号 (U+0022 '"') 和冒号 (U+003A ':')。每个值使用 U+0022 '"' 字符和 Go 字符串文字语法。

      Here's a simple example on the playground

      【讨论】:

      • mapstructure 在撰写本文时似乎支持其文档中的省略。
      猜你喜欢
      • 2022-12-06
      • 1970-01-01
      • 1970-01-01
      • 2013-11-06
      • 2013-07-18
      • 2011-02-13
      • 2021-09-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多