arrays - json 解码后缺少结构对象的嵌套数组

标签 arrays json go struct unmarshalling

当对象具有嵌套的结构对象数组时,我在将字符串解码回结构对象时遇到了一些问题。我使用以下代码作为我的问题的演示:

json字符串为

const myStr = `{
  "name": "test_session1",
  "shared_items:": [
    {
      "id": 0,
      "name": ".aspnet"
    },
    {
      "id": 1,
      "name": ".bash_profile"
    }
  ]
}`

我有两个结构如下,Session 是父结构,SharedItem 是关联的子结构(ren):

type Session struct {
    ID              uint64           `json:"id"`
    Name            string           `json:"name,omitempty"`
    SharedItems     []SharedItem `json:"shared_items"`
}

type SharedItem struct {
    ID          uint64 `json:"id"`
    Name        string `json:"name"`
}

我尝试了以下方法来解码 json 字符串,但看起来 SharedItem 对象的嵌套数组丢失了,因为我看到 sess 对象有 0 共享项目,这不是我所期望的。

func main() {
    var sess Session
    if err := json.Unmarshal([]byte(myStr), &sess); err != nil {
        panic(err)
    }
    fmt.Printf("sess name is: %s, and has %d shared items\n", sess.Name, len(sess.SharedItems)) // printed: sess name is test_session1, and has 0 shared items
}

这是我的 go playground 的链接:https://play.golang.org/p/a-y5T3tut6g

最佳答案

json 解码的 Golang 规范描述了这一切

To unmarshal JSON into a struct, Unmarshal matches incoming object keys to the keys used by Marshal (either the struct field name or its tag), preferring an exact match but also accepting a case-insensitive match. By default, object keys which don't have a corresponding struct field are ignored (see Decoder.DisallowUnknownFields for an alternative).

在 json 中,共享项目的 json 对象有 : 冒号,我们可以看到它是 shared_items: 而不是 shared_items是我们的json标签

  "shared_items:": [
    {
      "id": 0,
      "name": ".aspnet"
    },
    {
      "id": 1,
      "name": ".bash_profile"
    }
  ]

要么删除 : 要么附加到你的 struct json 标签中以匹配相同的标签。

package main

import (
    "fmt"
    "encoding/json"
)

type Session struct {
    Name            string           `json:"name,omitempty"`
    SharedItems     []SharedItem    `json:"shared_items"`
}

type SharedItem struct {
    ID          uint64 `json:"id"`
    Name        string `json:"name"`
}

const myStr = `{"name":"test_session1","shared_items":[{"id":0,"name":".aspnet"},{"id":1,"name":".bash_profile"}]}`

func main() {
    var sess Session

    if err := json.Unmarshal([]byte(myStr), &sess); err != nil {
        panic(err)
    }
    fmt.Println(sess)
    fmt.Printf("sess name is: %s, and has %d shared items\n", sess.Name, len(sess.SharedItems))
}

Playground example

关于arrays - json 解码后缺少结构对象的嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50035469/

相关文章:

arrays - 在 Golang 中获取指针数组的长度

java - 为什么java数组的最大大小是Integer.MAX_VALUE/7?

json - 无法在 Slack 线程中回复使用 JSON 发出 http post 请求

java - 我可以忽略 ObjectMapper 中的 MismatchedInputException 吗?

json - 无法使用带有空格的键名解码 JSON

mongodb - 在 golang 中使用 revel 框架创建一个新的 mongodb 数据库

c - 传入指针作为参数以获取字符串长度

php - 在 PHP 中组合多个数组值

JavaScript 函数多次调用

arrays - MongoDB:如何计算键中值的数量