我正在golang中创建一个json响应。我有一个问题,我能够生成一个json,例如:
{
"Name" : "Country",
"Value" : "abc"
}
name和value的值可以根据用户而变化,我使用的结构类似于:
type xAxis struct {
Name string,
Value string
}
我希望我的json看起来像这样:
{
"Country" : "abc"
}
是否可以像这样创建json?
您可以通过编写自定义MarshalJSON
函数来覆盖Go的json包封送结构的方式:
type xAxis struct {
Name string
Value string
}
func (a xAxis) MarshalJSON() ([]byte, error) {
return json.Marshal(map[string]interface{}{a.Name: a.Value})
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句