gpt4 book ai didi

json - 我可以在 golang 的 json 中将用户定义的值作为数据类型吗

转载 作者:IT王子 更新时间:2023-10-29 02:05:36 26 4
gpt4 key购买 nike

我正在 golang 中创建一个 json 响应。我有一个问题,我能够生成一个 json,例如:

{
"Name" : "Country",
"Value" : "abc"
}

name 和 value 的值可以根据用户而改变,我使用的结构如下:

type xAxis struct {
Name string,
Value string
}

我希望我的 json 看起来像这样:

{
"Country" : "abc"
}

是否可以像这样创建 json?

最佳答案

您可以通过编写自定义 MarshalJSON 函数来覆盖 Go 的 json 包编码(marshal)结构的方式:

type xAxis struct {
Name string
Value string
}

func (a xAxis) MarshalJSON() ([]byte, error) {
return json.Marshal(map[string]interface{}{a.Name: a.Value})
}

尝试一下:http://play.golang.org/p/G_E4IpNYIz

关于json - 我可以在 golang 的 json 中将用户定义的值作为数据类型吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27777092/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com