go - 为什么在 json.Unmarshal() 之后我得到一个空结构?
问题描述
编码器。我完全是新手,对 json.Unmarshal 输出有点困惑:
package main
import (
"encoding/json"
"fmt"
)
func main() {
s := `[{"First":"James","Last":"Bond","Age":32,"Sayings":["Shaken, not stirred","Youth is no guarantee of innovation","In his majesty's royal service"]},{"First":"Miss","Last":"Moneypenny","Age":27,"Sayings":["James, it is soo good to see you","Would you like me to take care of that for you, James?","I would really prefer to be a secret agent myself."]},{"First":"M","Last":"Hmmmm","Age":54,"Sayings":["Oh, James. You didn't.","Dear God, what has James done now?","Can someone please tell me where James Bond is?"]}]`
var res []struct{}
err := json.Unmarshal([]byte(s), &res)
if err != nil {
fmt.Println(err)
}
fmt.Println(res)
}
输出:
[{} {} {}]
为什么是空的?你可以在这里试试:https: //play.golang.org/p/yztOLJADIXx
解决方案
如果您想在不知道其字段的情况下解组 JSON 对象,请使用map[string]interface{}
:
package main
import (
"encoding/json"
"fmt"
)
func main() {
s := `[{"First":"James","Last":"Bond","Age":32,"Sayings":["Shaken, not stirred","Youth is no guarantee of innovation","In his majesty's royal service"]},{"First":"Miss","Last":"Moneypenny","Age":27,"Sayings":["James, it is soo good to see you","Would you like me to take care of that for you, James?","I would really prefer to be a secret agent myself."]},{"First":"M","Last":"Hmmmm","Age":54,"Sayings":["Oh, James. You didn't.","Dear God, what has James done now?","Can someone please tell me where James Bond is?"]}]`
var res []map[string]interface{}
err := json.Unmarshal([]byte(s), &res)
if err != nil {
fmt.Println(err)
}
fmt.Println(res)
}
在这里试试:https: //play.golang.org/p/iPlBgguE8Kk
但是,如果您知道要解组的字段的名称,则应该定义结构。在您的情况下,它看起来像这样:
type Person struct {
First string `json:"First"`
Last string `json:"Last"`
Age int `json:"Age"`
Sayings []string `json:"Sayings"`
}
在此处尝试此解决方案:https: //play.golang.org/p/jCrCteYTaIf
推荐阅读
- c++ - `std::find()` 用字符串产生奇怪的结果
- python - 给定一个平衡的整数二叉树和一个整数 B,计算对 (a, b) 的数量,其中: a 是 b 的祖先。和 val <=B 的总和?
- javascript - 我不能使用 node.js 中另一个模块的导出函数
- authentication - 在 values.yaml 中更改 keycloak 的基本路径不会更改它在点击 http:// 时访问的 URL
: / - r - 如何将列表中数据框的名称放在每个相应的行中
- python - 如何在 Typescript 中模仿 Python 中的 kwargs
- html - 随机数不打印结果
- ios - -canOpenURL:URL 失败:“fbauth2:/”-错误:“操作无法完成。(OSStatus 错误 -10814。)”SWIFT 5 FBDSKCoreKit 5
- node.js - 如何将文件从 React 上传到 Express 服务器?
- assembly - 汇编 mov 指令无法识别