How to Customize JSON Unmarshaling with String Split in Go?

Linda Hamilton
Release: 2024-10-26 04:23:02
Original
483 people have browsed it

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

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

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

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!