Home >Backend Development >Golang >How to Customize JSON Unmarshaling with String Split in Go?
Custom Unmarshal with String Split in Go
When dealing with JSON data, the need often arises to transform or customize the unmarshaling process for specific data types. In this case, we want to split a JSON string containing comma-separated values into a []string slice during unmarshalling.
To achieve this, let's implement a custom unmarshaler for the []string type:
<code class="go">type strslice []string func (ss *strslice) UnmarshalJSON(data []byte) error { var s string if err := json.Unmarshal(data, &s); err != nil { return err } *ss = strings.Split(s, "-") return nil }</code>
This custom unmarshaler takes the raw JSON data as input and converts it to a slice of strings by splitting it on the specified delimiter ("-" in this case).
In our original struct, we can now use this custom type for the Subjects field:
<code class="go">type Student struct { StudentNumber int `json:"student_number"` Name string `json:"name"` Subjects strslice `json:"subjects"` }</code>
This allows us to unmarshal the JSON data directly into the struct, with the Subjects field automatically split into individual strings:
<code class="go">json := `{"student_number":1234567, "name":"John Doe", "subjects":"Chemistry-Maths-History-Geography"}` var s Student if err := json.Unmarshal([]byte(json), &s); err != nil { panic(err) } fmt.Println(s) // Output: {1234567 John Doe [Chemistry Maths History Geography]}</code>
The above is the detailed content of How to Customize JSON Unmarshaling with String Split in Go?. For more information, please follow other related articles on the PHP Chinese website!