gpt4 book ai didi

json - 无法将字符串解码到 Go 结构字段中

转载 作者:IT王子 更新时间:2023-10-29 01:52:13 24 4
gpt4 key购买 nike

我有以下(不完整类型)(这是来自 list 端点 v2 架构 1 https://docs.docker.com/registry/spec/manifest-v2-1/ 的 docker API 的响应)

type ManifestResponse struct {
Name string `json:"name"`
Tag string `json:"tag"`
Architecture string `json:"architecture"`

FsLayers []struct {
BlobSum string `json:"blobSum"`
} `json:"fsLayers"`

History []struct {
V1Compatibility struct {
ID string `json:"id"`
Parent string `json:"parent"`
Created string `json:"created"`
} `json:"v1Compatibility"`
} `json:"history"`
}

同时得到以下响应:

 { "schemaVersion": 1,
"name": "library/redis",
"tag": "latest",
"architecture": "amd64",
"history": [
{
"v1Compatibility": "{\"id\":\"ef8a93741134ad37c834c32836aefbd455ad4aa4d1b6a6402e4186dfc1feeb88\",\"parent\":\"9c8b347e3807201285053a5413109b4235cca7d0b35e7e6b36554995cfd59820\",\"created\":\"2017-10-10T02:53:19.011435683Z\"}"
}
]
}

尝试使用以下代码片段对其进行反序列化时:

var jsonManResp ManifestResponse                                                                                                                                                                                                                                                
if err = json.NewDecoder(res.Body).Decode(&jsonManResp); err != nil {
log.Fatal(err)
}

我收到以下错误:

json: cannot unmarshal string into Go struct field .v1Compatibility of type struct { ID string "json:\"id\""; Parent string "json:\"parent\""; Created string "json:\"created\"" }

完整 Playground 代码:https://play.golang.org/p/tHzf9GphWX

可能是什么问题?

最佳答案

问题是 v1Compatibility 是 JSON 中的字符串值;该值恰好是 JSON 内容,但它在 JSON 字符串中,因此不能一步解码。您可以分两次将其解码:

type ManifestResponse struct {
Name string `json:"name"`
Tag string `json:"tag"`
Architecture string `json:"architecture"`

FsLayers []struct {
BlobSum string `json:"blobSum"`
} `json:"fsLayers"`

History []struct {
V1CompatibilityRaw string `json:"v1Compatibility"`
V1Compatibility V1Compatibility
} `json:"history"`
}

type V1Compatibility struct {
ID string `json:"id"`
Parent string `json:"parent"`
Created string `json:"created"`
}

然后:

var jsonManResp ManifestResponse
if err := json.Unmarshal([]byte(exemplar), &jsonManResp); err != nil {
log.Fatal(err)
}
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
}

这里的工作 Playground 示例:https://play.golang.org/p/QNsu5_63E0

关于json - 无法将字符串解码到 Go 结构字段中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47063079/

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