Home > Backend Development > Golang > How Can I Successfully Unmarshal JSON Data to Interface Types in Go?

How Can I Successfully Unmarshal JSON Data to Interface Types in Go?

Patricia Arquette
Release: 2025-01-02 20:51:38
Original
790 people have browsed it

How Can I Successfully Unmarshal JSON Data to Interface Types in Go?

Unmarshalling to Interface Types

One of the challenges in Go's RPC and JSON packages is unmarshalling to interface types. Let's dissect this issue and explore its solution.

The Problem

When attempting to unmarshal to an interface type, we encounter errors like "json: cannot unmarshal object into Go value of type main.Foo." This occurs because the reflector cannot determine the appropriate concrete type to instantiate for the incoming marshaled data.

The Solution

The issue arises from the lack of type information available to the reflector during unmarshalling. For example, while marshalling is possible from interface type variables, unmarshalling is not due to the reflector's inability to identify the corresponding concrete type.

To solve this problem, frameworks like Java's Json (jackson) employ annotations to provide additional type information. However, in Go, we can implement the Unmarshaler interface for custom types to handle the unmarshalling process ourselves.

Implementing Unmarshaler

Here's an example of implementing the Unmarshaler interface for our custom type RawString:

type RawString string

func (m *RawString) MarshalJSON() ([]byte, error) {
    return []byte(*m), nil
}

func (m *RawString) UnmarshalJSON(data []byte) error {
    *m += RawString(data)
    return nil
}
Copy after login

Now, we can unmarshal JSON data into a RawString instance:

const data = `{"i":3, "S":{"phone": {"sales": "2223334444"}}}`

type A struct {
    I int64
    S RawString `sql:"type:json"`
}

func main() {
    a := A{}
    if err := json.Unmarshal([]byte(data), &a); err != nil {
        log.Fatal("Unmarshal failed", err)
    }
    fmt.Println("Done", a)
}
Copy after login

By providing the Unmarshaler implementation for our custom type, we can unmarshal JSON data without encountering the aforementioned error.

The above is the detailed content of How Can I Successfully Unmarshal JSON Data to Interface Types in Go?. For more information, please follow other related articles on the PHP Chinese website!

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