如何处理结构体(Struct)中的 JSON 键与 JSON 响应不同的情况?

huangapple go评论70阅读模式
英文:

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)
}

huangapple
  • 本文由 发表于 2016年9月18日 04:37:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/39551498.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定