"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Customize JSON Unmarshaling with String Split in Go?

How to Customize JSON Unmarshaling with String Split in Go?

Published on 2024-11-01
Browse:317

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:

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
}

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:

type Student struct {
    StudentNumber int      `json:"student_number"`
    Name          string   `json:"name"`
    Subjects      strslice `json:"subjects"`
}

This allows us to unmarshal the JSON data directly into the struct, with the Subjects field automatically split into individual strings:

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]}
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3