Home > Article > Backend Development > 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>
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>
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!