How to Unmarshal JSON Data with Tagged Fields in Go?

Patricia Arquette
Release: 2024-10-30 08:28:27
Original
544 people have browsed it

How to Unmarshal JSON Data with Tagged Fields in Go?

How to Unmarshal JSON with Tagged Fields

When unmarshaling JSON into a struct, it may be necessary to specify how certain fields are handled. To do this, tags can be added to the struct fields to provide additional information to the unmarshaling process.

In a scenario where you need to unmarshal a JSON field as a string into a struct field with a tag, a simple solution using reflection can be implemented:

<code class="go">package main

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

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

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

func main() {
    var a A
    err := json.Unmarshal([]byte(data), &a)
    if err != nil {
        log.Fatal("Unmarshal failed", err)
    }

    rt := reflect.TypeOf(a)
    rv := reflect.ValueOf(&a)
    for i := 0; i < rt.NumField(); i++ {
        f := rt.Field(i)
        if f.Tag.Get("json") != "" {
            fv := rv.Elem().Field(i)
            fv.SetString(string(fv.Bytes()))
        }
    }

    fmt.Println("Done", a)
}</code>
Copy after login

However, a more elegant approach is available in Go that eliminates the need for reflection:

<code class="go">package main

import (
    "encoding/json"
    "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)
}</code>
Copy after login

The above is the detailed content of How to Unmarshal JSON Data with Tagged Fields 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!