首頁  >  文章  >  後端開發  >  如何在 Golang 中使用分隔符號將 JSON 字串解組為切片?

如何在 Golang 中使用分隔符號將 JSON 字串解組為切片?

Linda Hamilton
Linda Hamilton原創
2024-10-26 21:52:02236瀏覽

How to Unmarshal a JSON String into a Slice Using a Delimiter in Golang?

在Golang 中使用字串拆分進行自訂解組

問題:

將JSON 解組到在具有字段的結構體中,該結構體應該是字串切片,而JSON 值是需要使用分隔符號分割的單一字串。

<code class="json">{
  "student_number": 1234567,
  "name": "John Doe",
  "subjects": "Chemistry-Maths-History-Geography"
}</code>
<code class="go">type Student struct {
  StudentNumber int
  Name          string
  Subjects      []string
}</code>

答案:

定義一個自訂字串切片類型並實作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
  Name          string
  Subjects      strslice
}</code>

代碼示例:

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

const src = `{"student_number":1234567, "name":"John Doe", "subjects":"Chemistry-Maths-History-Geography"}`</code>

輸出:

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

以上是如何在 Golang 中使用分隔符號將 JSON 字串解組為切片?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn