英文:
How to deal with Struct having different json key than json response
问题
我有一个名为VideoInfo
的结构体,其中有一个名为embedCode
的键。我正在查询的API将嵌入代码返回为embed_code
。在解组响应时,我该如何确保embed_code
被赋值给embedCode
?
此外,是否有一种简单的方法可以将一个大的JSON字符串自动转换为结构体,或者只能使用映射(map)来实现?
英文:
I have a struct VideoInfo
that has a key in it called embedCode
. The API I am querying returns the embed code as embed_code
. During unmarshalling the response how do I ensure embed_code
goes into embedCode
?
Also is there an easy way to take a large json string and automatically turn it into a struct, or can one only use a map?
答案1
得分: 1
首先,结构体的字段必须以大写字母开头才能是公共的。所以你需要像这样写:
type VideoInfo struct {
EmbedCode string `json:"embed_code"`
}
并且查看文档以获取更多信息。
英文:
At first, struct's field must be start from capital letter to be public. So you need something like that:
type VideoInfo struct {
EmbedCode string `json:"embed_code"`
}
And look at documentation for more info.
答案2
得分: 1
关于重新映射字段名,请在结构声明中使用相应的注释:
type VideoInfo struct {
EmbedCode string `json:"embed_code"`
}
编组器/解组器只会处理公共字段,所以你需要将字段名大写。
关于转换整个结构体,是的,很容易实现。声明一个实例用于解组,并将引用传递给json.Unmarshal
方法(来自测试):
data, _ := json.Marshal(request)
var resp response.VideoInfo
if err := json.Unmarshal(data, &resp); err != nil {
t.Errorf("unexpected error, %v", err)
}
英文:
With respect to remapping the field names use the corresponding annotation in the structure declaration:
type VideoInfo struct {
EmbedCode string `json:"embed_code"`
}
The marshaller/un-marshaller will only process public field, so you need to capitalise the field name.
With respect to converting the whole structure, yes it is easy. Declare an instance to un-marshal into and pass a reference to the json.Unmarshal
method (from a test):
data, _ := json.Marshal(request)
var resp response.VideoInfo
if err := json.Unmarshal(data, &resp); err != nil {
t.Errorf("unexpected error, %v", err)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论