Home > Backend Development > Golang > How Can I Unmarshal JSON Data into an Interface Type in Go?

How Can I Unmarshal JSON Data into an Interface Type in Go?

Barbara Streisand
Release: 2024-12-20 09:22:11
Original
581 people have browsed it

How Can I Unmarshal JSON Data into an Interface Type in Go?

Unmarshal to an Interface Type

In RPC, marshalling to an interface type is straightforward since the object is local and the reflector can identify its underlying type. However, unmarshalling to an interface type presents a challenge.

The reflector cannot determine the concrete type to assign to the new instance that will receive the marshaled data. This limitation applies to all marshalling/unmarshalling operations.

To resolve this issue in some frameworks, additional information is provided to assist the reflector. For example, in Java Json(jackson), the JsonTypeInfo annotation specifies the class type.

In Go, implementing the Unmarshaler interface for your custom type can address this challenge. Consider the following example:

import (
    "encoding/json"
    "errors"
    "fmt"
    "log"
)

// RawString is a raw encoded JSON object.
// It implements Marshaler and Unmarshaler and can
// be used to delay JSON decoding or precompute a JSON encoding.
type RawString string

// MarshalJSON returns *m as the JSON encoding of m.
func (m *RawString) MarshalJSON() ([]byte, error) {
    return []byte(*m), nil
}

// UnmarshalJSON sets *m to a copy of data.
func (m *RawString) UnmarshalJSON(data []byte) error {
    if m == nil {
        return errors.New("RawString: UnmarshalJSON on nil pointer")
    }
    *m += RawString(data)
    return nil
}

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

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

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

The above is the detailed content of How Can I Unmarshal JSON Data into an Interface Type in Go?. 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