dongqi6964 2017-03-21 07:17
浏览 113
已采纳

在Golang中的json.Marshal之前添加密钥

I am creating a function to get array of object and save it into Struct. Then I want to convert it into JSON.

func GetCountry(msg string) []byte {
    var countries []*countryModel.Country

    countries = countryModel.GetAllCountry()

    jsResult, err := json.Marshal(countries)

    if err != nil {
        logger.Error(err, "Failed on GetCountry")
    }

    return jsResult
}

Here is the struct

type Country struct {
    Id           int    `json:"id"`
    CountryCode string `json:"country_code"`
    CountryName string `json:"country_name"`
    PhoneCode   string `json:"phone_code"`
    Icon         string `json:"icon"`
}

With that function, i get these result

[
  {
    "id": 2,
    "country_code": "MY",
    "country_name": "Malaysia",
    "phone_code": "+60",
    "icon": "no-data"
  },
  {
    "id": 2,
    "country_code": "MY",
    "country_name": "Malaysia",
    "phone_code": "+60",
    "icon": "no-data"
  }
]

How can i add a key named 'countries' for that JSON result? These what i am expect

{
    "countries" : 
        [
          {
            "id": 2,
            "country_code": "MY",
            "country_name": "Malaysia",
            "phone_code": "+60",
            "icon": "no-data"
          },
          {
            "id": 2,
            "country_code": "MY",
            "country_name": "Malaysia",
            "phone_code": "+60",
            "icon": "no-data"
          }
        ]
}

Please help

  • 写回答

1条回答 默认 最新

  • donglaoe2979 2017-03-21 07:24
    关注

    You could create a wrapper struct that contains an array of country structs, with json: "countries" after the declaration for the countries array, then call json.Marshal on the wrapper.

    What it looks like:

    type CountryWrapper struct {
      Countries []*countryModel.Country `json: "countries"`
    } 
    

    Then, in your method, instantiate as CountryWrapper{ Countries: countries }, and call json.Marshal on this object.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名