Home > Backend Development > Golang > How to Unmarshal a Comma-Separated String into a Slice in Go Using Custom Unmarshaling?

How to Unmarshal a Comma-Separated String into a Slice in Go Using Custom Unmarshaling?

DDD
Release: 2024-10-26 16:21:30
Original
676 people have browsed it

How to Unmarshal a Comma-Separated String into a Slice in Go Using Custom Unmarshaling?

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
}
Copy after login

In your struct definition, use the custom slice type for the "subjects" field:

type Student struct {
    StudentNumber int
    Name          string
    Subjects      SubjectSlice
}
Copy after login

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"}
Copy after login

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"},
}
Copy after login

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template