首頁  >  文章  >  後端開發  >  為什麼 JSON Unmarshal 在處理介面時返回 Map 而不是 Go 中的結構體?

為什麼 JSON Unmarshal 在處理介面時返回 Map 而不是 Go 中的結構體?

Barbara Streisand
Barbara Streisand原創
2024-10-25 09:26:02605瀏覽

Why Does JSON Unmarshal Return a Map Instead of a Struct in Go When Working with Interfaces?

JSON Unmarshal 傳回映射而不是預期的結構背後的秘密

Go 中的JSON 解組在處理介面和結構時可能會帶來挑戰。開發人員可能會遇到這樣的情況:解組過程產生映射而不是預期的結構,如給定程式碼片段中的情況:

<code class="go">import "encoding/json"
import "fmt"
import "reflect"

func main() {
    type Ping struct {
        ID int `json:"id"`
    }
    var ping interface{} = Ping{}
    if err := json.Unmarshal([]byte(`{"id":42}`), &ping); err != nil {
        panic(err)
    }
    fmt.Println("Unexpected:", ping) // Result: map[id:42]
}</code>

此行為的根本原因在於介面的抽象性質。當在介面上執行 JSON 解組時,結果是表示基礎類型欄位的對應。在上面的範例中,介面 Ping 持有一個具有單一鍵值對的對應:{“id”:42}。

要修正此問題並取得所需的結構,傳遞指標至關重要到特定的結構類型:

<code class="go">type Ping struct {
    ID int `json:"id"`
}
func main() {
    var ping Ping
    if err := json.Unmarshal([]byte(`{"id":42}`), &ping); err != nil {
        panic(err)
    }
    fmt.Println("Success:", ping) // Result: {42}
}</code>

透過將指標傳遞給Ping,JSON 解組過程將直接建立結構的實例並填充其字段,而不是建立映射。

或者,如果指向特定結構的指針不可用,您可以使用反射來動態建立指針,然後將其值指派給介面:

<code class="go">import "reflect"

func main() {
    var ping interface{} = Ping{}
    nptr := reflect.New(reflect.TypeOf(ping))
    if err := json.Unmarshal([]byte(`{"id":42}`), nptr.Interface()); err != nil {
        panic(err)
    }
    ping = nptr.Elem().Interface()
    fmt.Println("Reflect-Based:", ping) // Result: {42}
}</code>

以上是為什麼 JSON Unmarshal 在處理介面時返回 Map 而不是 Go 中的結構體?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn