通过显示json数组数据,下面的代码工作正常。以下是代码中正在运行的Json响应
{"provision":"provision section 1",
"subsets": [{"item":"milk"},{"payments": [{"price": "200 usd"}]}]}
现在我有新的json响应如下。在下面的新json响应中,参数子集现在被括号{}包围
{
"provision":{"subsets": [{"item":"milk"},{"payments": [{"price": "200 usd"}]}]}
}
如果我在代码中集成New json它会显示错误,无法将对象解组为Go struct field Head.Provision。任何解决对象问题的解决方案都将受到赞赏
这是代码
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
)
type Head struct {
Provision string `json:"provision"`
Subsets []Subset `json:"subsets"`
}
type Subset struct {
Payments []Payment `json:"payments"`
Item string `json:"item"`
}
type Payment struct {
Price string `json:"price"`
}
func main() {
/*
// old working json
m := []byte(`
{"provision":"provision section 1",
"subsets": [{"item":"milk"},{"payments": [{"price": "200 usd"}]}]}
`)
*/
// New json response not working
m := []byte(`
{
"provision":{"subsets": [{"item":"milk"},{"payments": [{"price": "200 usd"}]}]}
}
`)
r := bytes.NewReader(m)
decoder := json.NewDecoder(r)
val := &Head{}
err := decoder.Decode(val)
if err != nil {
log.Fatal(err)
}
fmt.Println(val.Provision)
// Subsets is a slice so you must loop over it
for _, s := range val.Subsets {
fmt.Println(s.Item)
// within Subsets, payment is also a slice
// then you can access each price
for _, a := range s.Payments {
fmt.Println(a.Price)
}
}
}
以下是我如何使用它。谢谢
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
)
type Head struct {
Provision Prov `json:"provision"`
//Subsets []Subset `json:"subsets"`
}
type Prov struct {
Subsets []Subset `json:"subsets"`
}
type Subset struct {
Payments []Payment `json:"payments"`
Item string `json:"item"`
}
type Payment struct {
Price string `json:"price"`
}
func main() {
m := []byte(`
{"provision":
{"subsets": [{"item":"milk"},{"payments": [{"price": "200 usd"}]},
{"item":"SUGAR"},{"payments": [{"price": "600 usd"}]}
]}
}
`)
r := bytes.NewReader(m)
decoder := json.NewDecoder(r)
val := &Head{}
err := decoder.Decode(val)
if err != nil {
log.Fatal(err)
}
//fmt.Println(val.Provision)
// Subsets is a slice so you must loop over it
for _, s := range val.Provision.Subsets {
fmt.Println(s.Item)
// within Subsets, payment is also a slice
// then you can access each price
for _, a := range s.Payments {
fmt.Println(a.Price)
}
}
}
type Head struct {
Provision Provision `json:"provision"`
}
type Provision struct {
Subsets []Subset `json:"subsets"`
}