我有一个 RESTful 服务,返回类似于下面显示的响应:
"Basket" : {
"Count": 1,
"Fruits": {[
{
"Name":"Mango",
"Season":"Summer"
},
{
"Name":"Fig",
"Season":"Winter"}
]}
}
我正在尝试创建 Go 语言模型来解码内容。以下是我试过的代码:
type Response struct {
Count int
Fruits []Fruit
}
type Fruit struct {
Name string
Season string
}
但是当我在我的测试代码中编码 Response 对象时,我没有看到类似的 json。 ( https://play.golang.org/p/EGKqfbwFvW ) 编码数据始终显示为:
{
"Count":100,
"Fruits":[
{"Name":"Mango","Season":"Summer"},
{"Name":"Fig","Season":"Winter"}
]
}
请注意 Fruits 在原始 json 中显示为数组 [] 而不是 {[]}。我如何在 golang 中为这个响应建模结构?
最佳答案
您的模型是完全正确和有效的,但 JSON 对象不是。 "Fruits"
如果它应该是键值对或者应该包含在 []
中,则没有名称不是{}
.
JSON obj 的格式应该是这样的:
{
"Basket" : {
"Count": 1,
"Fruits": [
{
"Name":"Mango",
"Season":"Summer"
},
{
"Name":"Fig",
"Season":"Winter"
}
]
}
}
实际上无效的 json 不应该工作 https://play.golang.org/p/yoW7t4NfI7
关于golang 中的 Json 解码类型模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41992035/