Custom Unmarshal with String Split in Go
When unmarshalling JSON into Go structs, the default behavior is to convert JSON values to the corresponding struct fields. However, there are scenarios where you may need to perform custom transformations during the unmarshalling process.
Consider a JSON object with "subjects" represented as a comma-separated string. To unmarshal this into a Go struct with "subjects" as a slice of strings, you need to split the string during unmarshalling.
One approach is to implement a custom unmarshaller for the "subjects" field using the json.Unmarshaler interface. Here's how you can achieve this:
type SubjectSlice []string // UnmarshalJSON implements custom unmarshalling for SubjectSlice. func (s *SubjectSlice) UnmarshalJSON(data []byte) error { var subjects string err := json.Unmarshal(data, &subjects) if err != nil { return err } *s = strings.Split(subjects, "-") return nil }
In your struct definition, use the custom slice type for the "subjects" field:
type Student struct { StudentNumber int Name string Subjects SubjectSlice }
When you unmarshal the JSON using this custom unmarshaller, the "subjects" field will be automatically split into a slice of strings.
For example, consider the following JSON:
{"student_number":1234567, "name":"John Doe", "subjects":"Chemistry-Maths-History-Geography"}
Unmarshaling it into the Student struct with the custom unmarshaller would result in:
s := Student{ StudentNumber: 1234567, Name: "John Doe", Subjects: []string{"Chemistry", "Maths", "History", "Geography"}, }
By implementing custom unmarshallers, you can handle complex data transformations during unmarshalling, making it a powerful tool for working with custom data structures in JSON.
The above is the detailed content of How to Unmarshal a Comma-Separated String into a Slice in Go Using Custom Unmarshaling?. For more information, please follow other related articles on the PHP Chinese website!