未編組資料的型別斷言
在分散式系統中,資料通常會以 JSON 字串交換。從訊息佇列中擷取 JSON 資料時,您可能會遇到需要將資料反序列化為 Interface{},然後執行類型斷言以確定資料實際結構類型的場景。
問題
將接收到的 JSON 字串解組到介面{}並嘗試輸入斷言結果時,您可能會遇到意外結果。您獲得的不是預期的結構類型,而是映射[字串]介面{}。
解決方案
JSON 解組到介面{} 的預設行為會產生型別例如bool、float64、string、[]interface{} 和map[string] interface{}。由於 Something1 和 Something2 是自訂結構,因此 JSON 解組器無法辨識它們。
要解決這個問題,有兩種主要方法:
1。直接解組到自訂結構
程式碼:
var input Something1 json.Unmarshal([]byte(msg), &input) // Type assertions and processing can be performed here var input Something2 json.Unmarshal([]byte(msg), &input) // Type assertions and processing can be performed here
2.從地圖介面解壓縮
程式碼:
var input interface{} json.Unmarshal([]byte(msg), &input) // Unpack the data from the map switch v := input.(type) { case map[string]interface{}: // Extract the data from the map and assign it to custom structs }
高階方法
要接受更通用的解決方案,考慮創建一個「Unpacker」結構來處理解群組和類型斷言
代碼:
type Unpacker struct { Data interface{} } func (u *Unpacker) UnmarshalJSON(b []byte) error { smth1 := &Something1{} err := json.Unmarshal(b, smth1) if err == nil && smth1.Thing != "" { u.Data = smth1 return nil } smth2 := &Something2{} err = json.Unmarshal(b, smth2) if err != nil { return err } u.Data = smth2 return nil }
結論結論
結論結論結論結論結論結論結論透過使用其中一種方法,您可以成功執行type對首先從 JSON 字串解組到介面{}的資料的斷言。方法的選擇取決於您應用程式的特定要求。以上是如何在 Go 中對未編組的 JSON 資料執行類型斷言?的詳細內容。更多資訊請關注PHP中文網其他相關文章!