ホームページ  >  記事  >  バックエンド開発  >  Golang で JSON 文字列フィールドを文字列のスライスにアンマーシャリングする方法

Golang で JSON 文字列フィールドを文字列のスライスにアンマーシャリングする方法

Barbara Streisand
Barbara Streisandオリジナル
2024-10-27 05:52:29296ブラウズ

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

Golang で文字列分割を使用したカスタム アンマーシャリング

問題:

JSON を Golang にアンマーシャリングするstruct。1 つの文字列フィールド (例: "subjects") は、区切り文字 (例: '-') に基づいて文字列のスライスに分割する必要があります。

解決策:

文字列フィールドのスライスにカスタム アンマーシャラーを実装します。これには、json.Unmarshaler インターフェイスを実装する新しいデータ型の作成が含まれます:

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

構造体でこのカスタム型を使用します:

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

JSON をアンマーシャリングするときに、「サブジェクト」 " フィールドは文字列のスライスに自動的に分割されます:

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

出力:

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

以上がGolang で JSON 文字列フィールドを文字列のスライスにアンマーシャリングする方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。