首頁 > 後端開發 > Golang > 主體

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

Linda Hamilton
發布: 2024-10-26 21:52:02
原創
235 人瀏覽過

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中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!