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.
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>
In this case, the goal is to unmarshal the "S" field in the JSON as a string into the struct A.
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>
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.
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!