問題:無法將字串解組到Go Struct 欄位
在處理來自Docker API 的/manifests 端點(v2 架構1)的JSON 回應時,嘗試將其反序列化為Go 結構時遇到錯誤。錯誤,「json:無法將字串解組到Go 結構欄位.v1Compatibility of type struct { ID string "json:"id""; Parent string "json:"parent""; Created string "json:"created"" }" ,表示相關欄位的類型應與提供的JSON 資料不同。
以下程式碼片段代表有問題的部分:
type ManifestResponse struct { // ... other fields History []struct { V1Compatibility struct { ID string `json:"id"` Parent string `json:"parent"` Created string `json:"created"` } `json:"v1Compatibility"` } `json:"history"` } // ... if err = json.NewDecoder(res.Body).Decode(&jsonManResp); err != nil { log.Fatal(err) }
出現此問題的原因是欄位 V1Compatibility 是 JSON 回應中的字串。然而,Golang 希望它是一個 V1Compatibility 型別的結構。為了解決這個問題,需要採用兩遍解組方法。
下面修改後的程式碼示範了解決方法:
type ManifestResponse struct { // ... other fields 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 }
在此解決方案中,引入了 V1CompatibilityRaw 欄位來容納字串值來自 JSON 回應。解組的第二遍用實際的結構資料填入 V1Compatibility 欄位。
此方法可以將 JSON 回應成功反序列化為所需的 Go 結構。
以上是為什麼我的 Go 結構無法將 JSON 字串解組到巢狀結構欄位中,如何使用兩遍解組方法修復它?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

goimpactsdevelopmentpositationality throughspeed,效率和模擬性。 1)速度:gocompilesquicklyandrunseff,IdealforlargeProjects.2)效率:效率:ITScomprehenSevestAndardArdardArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdEcceSteral Depentencies,增強的Depleflovelmentimency.3)簡單性。

C 更適合需要直接控制硬件資源和高性能優化的場景,而Golang更適合需要快速開發和高並發處理的場景。 1.C 的優勢在於其接近硬件的特性和高度的優化能力,適合遊戲開發等高性能需求。 2.Golang的優勢在於其簡潔的語法和天然的並發支持,適合高並發服務開發。

Golang在实际应用中表现出色,以简洁、高效和并发性著称。1)通过Goroutines和Channels实现并发编程,2)利用接口和多态编写灵活代码,3)使用net/http包简化网络编程,4)构建高效并发爬虫,5)通过工具和最佳实践进行调试和优化。

Go語言的核心特性包括垃圾回收、靜態鏈接和並發支持。 1.Go語言的並發模型通過goroutine和channel實現高效並發編程。 2.接口和多態性通過實現接口方法,使得不同類型可以統一處理。 3.基本用法展示了函數定義和調用的高效性。 4.高級用法中,切片提供了動態調整大小的強大功能。 5.常見錯誤如競態條件可以通過gotest-race檢測並解決。 6.性能優化通過sync.Pool重用對象,減少垃圾回收壓力。

Go語言在構建高效且可擴展的系統中表現出色,其優勢包括:1.高性能:編譯成機器碼,運行速度快;2.並發編程:通過goroutines和channels簡化多任務處理;3.簡潔性:語法簡潔,降低學習和維護成本;4.跨平台:支持跨平台編譯,方便部署。

關於SQL查詢結果排序的疑惑學習SQL的過程中,常常會遇到一些令人困惑的問題。最近,筆者在閱讀《MICK-SQL基礎�...

golang ...


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

Atom編輯器mac版下載
最受歡迎的的開源編輯器

ZendStudio 13.5.1 Mac
強大的PHP整合開發環境

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器

禪工作室 13.0.1
強大的PHP整合開發環境