我已经查看了许多使用go解析JSON的示例,并了解了基础知识。但我无法正确解析一组对象。我为对象创建了一个结构但没有骰子!
这是一个关于它的游乐场: playground
package main
import (
"encoding/json"
"fmt"
)
type Outer struct {
Number int `json: "number"`
Message string `json: "message"`
Person []Person `json: "person"`
}
type Person struct {
craft string `json: "craft"`
name string `json: "name"`
}
func main() {
text := `{"people": [{"craft": "ISS", "name": "Sergey Rizhikov"}, {"craft": "ISS", "name": "Andrey Borisenko"}, {"craft": "ISS", "name": "Shane Kimbrough"}, {"craft": "ISS", "name": "Oleg Novitskiy"}, {"craft": "ISS", "name": "Thomas Pesquet"}, {"craft": "ISS", "name": "Peggy Whitson"}], "message": "success", "number": 6}`
textBytes := []byte(text)
people1 := Outer{}
err := json.Unmarshal(textBytes, &people1)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(people1)
}
答案 0 :(得分:4)
您的代码中有几个错误:
people
字段,但在struct声明中有person
。 Person
结构字段中必须以大写字母开头。json:"name"
无效时删除json标记json: "name"
中的空格。这是固定的version.
答案 1 :(得分:0)
更新了修复问题的代码:
package main
import (
"encoding/json"
"fmt"
)
type Outer struct {
Number int `json:"number"`
Message string `json:"message"`
Person []Person `json:"person"`
}
type Person struct {
Craft string `json:"craft"`
Name string `json:"name"`
}
func main() {
text := `{"person": [{"craft": "ISS", "name": "Sergey Rizhikov"}, {"craft": "ISS", "name": "Andrey Borisenko"}, {"craft": "ISS", "name": "Shane Kimbrough"}, {"craft": "ISS", "name": "Oleg Novitskiy"}, {"craft": "ISS", "name": "Thomas Pesquet"}, {"craft": "ISS", "name": "Peggy Whitson"}], "message": "success", "number": 6}`
textBytes := []byte(text)
people1 := Outer{}
err := json.Unmarshal(textBytes, &people1)
if err != nil {
fmt.Println(err)
return
}
b, err := json.Marshal(people1)
if err != nil {
fmt.Println("marshalling error")
return
}
fmt.Println("Data : ", string(b))
}
输出:数据:{“数字”:6,“消息”:“成功”,“人”:[{“craft”:“ISS”,“name”:“Sergey Rizhikov”},{“craft” :“ISS”,“name”:“Andrey Borisenko”},{“craft”:“ISS”,“name”:“Shane Kimbrough”},{“craft”:“ISS”,“name”:“Oleg Novitskiy “},{”craft“:”ISS“,”name“:”Thomas Pesquet“},{”craft“:”ISS“,”name“:”Peggy Whitson“}}} 在操场上办理登机手续:https://play.golang.org/p/tdNpgUAOLVF
答案 2 :(得分:-1)
将“人员结构”字段更新为公开,例如:
type AutoGenerated struct {
People []People `json:"people"`
Message string `json:"message"`
Number int `json:"number"`
}
type People struct {
Craft string `json:"craft"`
Name string `json:"name"`
}
使用该工具并自动为您提供帮助。 Best JSON To Golang Converter