Home > Backend Development > Golang > How Can I Effectively Handle JSON Marshaling and Unmarshaling with Go's Interface Types?

How Can I Effectively Handle JSON Marshaling and Unmarshaling with Go's Interface Types?

DDD
Release: 2024-12-15 15:35:10
Original
534 people have browsed it

How Can I Effectively Handle JSON Marshaling and Unmarshaling with Go's Interface Types?

Marshaling to Interface Types

JSON marshaling and unmarshaling can present challenges when working with interface types. This article delves into the difficulties and provides solutions.

Marshaling from Interface

Marshaling from an interface type is straightforward because the underlying type is known locally, allowing the reflector to identify it.

Unmarshaling to Interface

Unmarshaling to an interface type, however, is problematic. Without knowing the concrete type, the reflector cannot instantiate a new instance to receive the marshaled data.

Resolving the Issue

To address this limitation, one approach is to implement the Unmarshaler interface for custom types. Refer to the example below:

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

// RawString represents a raw JSON object.
type RawString string

// Implement the Marshaler and Unmarshaler interfaces.
func (m *RawString) MarshalJSON() ([]byte, error)   { return []byte(*m), nil }
func (m *RawString) UnmarshalJSON(data []byte) error { *m += RawString(data); return nil }

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

// Example struct.
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

In this example, RawString implements both Marshaler and Unmarshaler, allowing for custom marshaling and unmarshaling. The main function then uses json.Unmarshal to decode the JSON data into an instance of A.

The above is the detailed content of How Can I Effectively Handle JSON Marshaling and Unmarshaling with Go's Interface Types?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template