How do you unmarshal JSON data with custom field tags in Go?

DDD
Release: 2024-10-30 01:31:29
Original
909 people have browsed it

How do you unmarshal JSON data with custom field tags in Go?

Unmarshalling JSON with Custom Field Tags

Introduction

Working with JSON data often involves converting it into structs for further processing. However, challenges arise when structs contain fields with custom tags that impact the unmarshalling process. This article demonstrates how to handle such scenarios using Go's reflection capabilities.

Problem Definition

In this particular situation, the goal is to unmarshal JSON data into a struct where one of its fields has a tag that indicates it should be treated as a JSON string. Let's consider this example:

<code class="go">const data = `{
    "I": 3,
    "S": {
        "phone": {
            "sales": "2223334444"
        }
    }
}`

type A struct {
    I int64
    S string `sql:"type:json"`
}</code>
Copy after login

In this case, the goal is to unmarshal the "S" field in the JSON as a string into the struct A.

Solution

Go provides a built-in UnmarshalJSON method that allows for custom unmarshalling behavior. By creating a new type, implementing the MarshalJSON and UnmarshalJSON methods, we can achieve the desired result:

<code class="go">import (
    "encoding/json"
    "errors"
    "log"
    "fmt"
)

// 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)
}</code>
Copy after login

In this solution, the RawString type implements the MarshalJSON and UnmarshalJSON methods to control how JSON data is encoded and decoded, essentially allowing the "S" field to be treated as a string during unmarshalling.

Conclusion

By leveraging Go's reflection capabilities and custom unmarshalling methods, it is possible to handle complex JSON unmarshalling scenarios even when fields have specific tags that require special treatment.

The above is the detailed content of How do you unmarshal JSON data with custom field tags 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!