ホームページ >バックエンド開発 >Golang >ネストされた JSON 構造を処理し、「文字列を Go 構造体フィールドにアンマーシャリングできません」エラーを回避する方法

ネストされた JSON 構造を処理し、「文字列を Go 構造体フィールドにアンマーシャリングできません」エラーを回避する方法

DDD
DDDオリジナル
2024-11-25 08:34:10242ブラウズ

How to Handle Nested JSON Structures and Avoid

入れ子構造を使用した 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 サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。