Home > Backend Development > Golang > Why does interface assertion fail during JSON deserialization?

Why does interface assertion fail during JSON deserialization?

Patricia Arquette
Release: 2024-11-24 15:32:16
Original
606 people have browsed it

Why does interface assertion fail during JSON deserialization?

Interface Assertion Fails During JSON Deserialization

When attempting to assert an interface to a specific struct type after deserializing from JSON, an error occurs:

panic: interface conversion: interface {} is map[string]interface {},
not main.Data
Copy after login

This issue arises because the assertion is being made to an incompatible type. An interface can only be converted to a specific type if it was originally assigned a value of that type.

In the provided code, the interface anInterface is assigned the value of the Data struct AData. Therefore, anInterface can safely be asserted to Data.

type Data struct {
    Content string
    Links   []string
}

func main() {
    var AData, AData2 Data
    var anInterface interface{}

    // populate data
    AData.Content = "hello world"
    AData.Links = []string{"link1", "link2", "link3"}
    anInterface = AData
    AData2 = anInterface.(Data)
}
Copy after login

Conversely, if the interface anInterface were assigned a value of type map[string]interface{}, it could not be asserted to Data.

To directly deserialize JSON data into a Data struct, use the json.Unmarshal() function.

var AData2 Data

err = json.Unmarshal([]byte(value), &AData2)
if err != nil {
    panic(err)
}
Copy after login

The above is the detailed content of Why does interface assertion fail during JSON deserialization?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template