如何使json响应在go中正常运行

时间:2019-03-14 00:27:03

标签: go

下面的代码通过显示json数组数据可以正常工作。 这是下面代码中有效的Json响应

 {"provision":"provision section 1",
    "subsets": [{"item":"milk"},{"payments": [{"price": "200 usd"}]}]}

现在我有New json响应,如下所示。现在,在新的json响应中,参数 subsets 现在是 用方括号 {}

包围
{
"provision":{"subsets": [{"item":"milk"},{"payments": [{"price": "200 usd"}]}]}
}

如果我将New json集成到代码中,则会显示错误无法将对象解组到Go结构字段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)
        }
    }


}

2 个答案:

答案 0 :(得分: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)
        }
    }


}

答案 1 :(得分:0)

type Head struct {
    Provision Provision `json:"provision"`
}

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

https://play.golang.org/p/3TgxBOng1qE的完整版本。