入れ子構造を使用した JSON のアンマーシャリング
複雑な JSON 応答を処理する場合、「文字列を Go 構造体フィールドにアンマーシャリングできません」のようなエラーが発生することがあります。 」。これは通常、JSON 応答に別の JSON 構造を表す文字列値が含まれている場合に発生します。
この不完全な Go struct ManifestResponse と、対応する 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 { V1Compatibility struct { ID string `json:"id"` Parent string `json:"parent"` Created string `json:"created"` } `json:"v1Compatibility"` } `json:"history"` }
{ "name": "library/redis", "tag": "latest", "architecture": "amd64", "history": [ { "v1Compatibility": "{\"id\":\"ef8a93741134ad37c834c32836aefbd455ad4aa4d1b6a6402e4186dfc1feeb88\",\"parent\":\"9c8b347e3807201285053a5413109b4235cca7d0b35e7e6b36554995cfd59820\",\"created\":\"2017-10-10T02:53:19.011435683Z\"}" } ] }
JSON を Go 構造体にアンマーシャリングすると、次のような問題が発生する可能性があります。 error:
json: cannot unmarshal string into Go struct field .v1Compatibility of type struct { ID string "json:\"id\""; Parent string "json:\"parent\""; Created string "json:\"created\"" }
この問題は、JSON 応答の v1Compatibility が JSON コンテンツを含む文字列値であるという事実に起因します。これに対処するために、2 パスのアンマーシャリングを実装できます:
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 }
このアプローチにより、2 つのパスでネストされた JSON 構造を処理できます。 -step アンマーシャリング プロセス。「文字列を Go 構造体フィールドにアンマーシャリングできません」エラーを防止します。
以上がネストされた JSON 構造を処理し、「文字列を Go 構造体フィールドにアンマーシャリングできません」エラーを回避する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。