如何让json响应在go中正常工作

问题描述 投票:0回答:2

通过显示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)
        }
    }


}
go
2个回答
1
投票

以下是我如何使用它。谢谢

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)
        }
    }


}

0
投票
type Head struct {
    Provision Provision `json:"provision"`
}

type Provision struct {
    Subsets []Subset `json:"subsets"`
}

https://play.golang.org/p/3TgxBOng1qE完整版在这里。

© www.soinside.com 2019 - 2024. All rights reserved.