Home  >  Article  >  Backend Development  >  How to Unmarshal a JSON String Field into a Slice of Strings in Golang?

How to Unmarshal a JSON String Field into a Slice of Strings in Golang?

Barbara Streisand
Barbara StreisandOriginal
2024-10-27 05:52:29296browse

How to Unmarshal a JSON String Field into a Slice of Strings in Golang?

Custom Unmarshal with String Split in Golang

Problem:

Unmarshalling JSON into a Golang struct, where one string field (e.g., "subjects") needs to be split into a slice of strings based on a delimiter (e.g., '-').

Solution:

Implement a custom unmarshaler for the slice of strings field. This involves creating a new data type that implements the json.Unmarshaler interface:

<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>

Use this custom type in the struct:

<code class="go">type Student struct {
    StudentNumber int      `json:"student_number"`
    Name          string   `json:"name"`
    Subjects      strslice `json:"subjects"`
}</code>

Now, when unmarshalling JSON, the "subjects" field will be automatically split into a slice of strings:

<code class="go">var s Student
err := json.Unmarshal([]byte(src), &s)
fmt.Println(s, err)</code>

Output:

{1234567 John Doe [Chemistry Maths History Geography]} <nil>

The above is the detailed content of How to Unmarshal a JSON String Field into a Slice of Strings in Golang?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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