首页 > 后端开发 > 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学习者快速成长!