我正在创建一个函数来获取对象数组并将其保存到Struct中。然后我想把它转换成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
}这是结构
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"`
}有了这个函数,我得到了这些结果
[
{
"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"
}
]如何为该JSON结果添加名为“countries”的键?这些都是我所期望的
{
"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"
}
]
}请帮帮忙
发布于 2017-03-21 07:24:03
您可以创建一个包含国家结构数组的包装器结构,在country数组的声明之后使用json: "countries",然后在包装器上调用json.Marshal。
它看起来是什么样子:
type CountryWrapper struct {
Countries []*countryModel.Country `json: "countries"`
} 然后,在您的方法中,实例化为CountryWrapper{ Countries: countries },并对该对象调用json.Marshal。
https://stackoverflow.com/questions/42920581
复制相似问题