Home >Backend Development >Golang >Why Does `json.Unmarshal` Fail When Using Interfaces Instead of Structs?

Why Does `json.Unmarshal` Fail When Using Interfaces Instead of Structs?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-26 04:26:12391browse

Why Does `json.Unmarshal` Fail When Using Interfaces Instead of Structs?

Unmarshaling JSON to Structs not Interfaces

When unmarshaling JSON data using json.Unmarshal, it's important to provide a concrete type for the destination variable to avoid unexpected conversions.

In your provided code, you define a function getFoo() that returns an interface containing a Foo struct. When you send this interface to json.Unmarshal, it interprets the value as a map, not a concrete struct.

To address this issue, you can either pass a pointer to the concrete struct within the interface or specify the concrete struct type directly in json.Unmarshal.

Here's an example using a pointer:

func getFoo() interface{} {
    return &Foo{"bar"}
}

func main() {
    fooInterface := getFoo()

    jsonBytes := []byte(`{"bar":"This is the new value of bar"}`)

    err := json.Unmarshal(jsonBytes, fooInterface)
    if err != nil {
        fmt.Println(err)
    }

    fmt.Println(fooInterface) // *main.Foo &{Bar:This is the new value of bar}
}

Alternatively, you can use type assertion to specify the concrete type:

func main() {
    fooInterface := getFoo()

    jsonBytes := []byte(`{"bar":"This is the new value of bar"}`)

    foo := fooInterface.(*Foo)
    err := json.Unmarshal(jsonBytes, foo)
    if err != nil {
        fmt.Println(err)
    }

    fmt.Println(foo) // &{Bar:This is the new value of bar}
}

By providing a concrete type, either through a pointer or type assertion, you ensure that json.Unmarshal directly unmarshals the data into the desired struct, preserving its type information and field values.

The above is the detailed content of Why Does `json.Unmarshal` Fail When Using Interfaces Instead of Structs?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn