当对象具有嵌套的结构对象数组时,我在将字符串解码回结构对象时遇到了一些问题。我使用以下代码作为我的问题的演示:
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))
}
关于arrays - json 解码后缺少结构对象的嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50035469/