“无法将字符串解组到 Go 结构字段”清单解码时出错
从 Docker API 反序列化 JSON 响应时,出现错误“ json: 无法将字符串解组到 Go 结构体字段 .v1 结构体类型的兼容性 { ID 字符串“json:”id”;遇到父字符串 "json:"parent"; 创建的字符串 "json:"created""}"。
问题源于响应结构与 Go 结构定义之间的不匹配。具体来说,JSON 响应中的“v1Compatibility”字段是包含嵌套 JSON 内容的字符串。 Go 结构体期望它是原生 Go 结构体,从而导致解组错误。
要解决此问题,可以采用两遍解组方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | type ManifestResponse struct {
Name string `json: "name" `
Tag string `json: "tag" `
Architecture string `json: "architecture" `
FsLayers []FSLayer `json: "fsLayers" `
History []HistEntry
}
type FSLayer struct {
BlobSum string `json: "blobSum" `
}
type HistEntry struct {
V1CompatibilityRaw string `json: "v1Compatibility" `
V1Compatibility V1Compatibility `json: "-" `
}
type V1Compatibility struct {
ID string `json: "id" `
Parent string `json: "parent" `
Created string `json: "created" `
}
|
登录后复制
在第一个过程中通过,JSON 响应被解组到带有 V1CompatibilityRaw 字段的 ManifestResponse 结构中populated:
1 2 3 4 | var jsonManResp ManifestResponse
if err := json.Unmarshal([]byte(response), &jsonManResp); err != nil {
log.Fatal(err)
}
|
登录后复制
在第二遍中,每个 V1CompatibilityRaw 字符串值都被解组到相应的 V1Compatibility 结构中:
1 2 3 4 5 6 7 | for i := range jsonManResp.History {
var comp V1Compatibility
if err := json.Unmarshal([]byte(jsonManResp.History[i].V1CompatibilityRaw), &comp); err != nil {
log.Fatal(err)
}
jsonManResp.History[i].V1Compatibility = comp
}
|
登录后复制
通过以这种方式处理嵌套的 JSON 内容,错误为已解决,并且正确的数据被解组到 Go 结构中。
以上是如何解决 Docker Manifest 解码中的'json:无法将字符串解组到 Go 结构字段”错误?的详细内容。更多信息请关注PHP中文网其他相关文章!