Golang unmarshall来自api.nal.usda.gov/ndb的JSON

时间:2017-04-11 15:02:51

标签: json go unmarshalling

您好我尝试将来自api.nal.usda.gov/ndb的JSON响应解组为struct,但它总是返回空:

{        []}

示例JSON:

{
    "list": {
        "q": "butter",
        "sr": "28",
        "ds": "any",
        "start": 0,
        "end": 50,
        "total": 4003,
        "group": "",
        "sort": "r",
        "item": [
            {
                "offset": 0,
                "group": "Branded Food Products Database",
                "name": "BLUE BUNNY, PEANUT BUTTER PANIC, ICE CREAM, POWERFUL PEANUT BUTTER ICE CREAM CHARGED WITH PEANUT BUTTER AND FUDGE SAUCES AND OVERLOADED WITH PEANUT BUTTER CUPS, UPC: 070640034086",
                "ndbno": "45011419",
                "ds": "BL"
            },
            {
                "offset": 1,
                "group": "Branded Food Products Database",
                "name": "BLUE BUNNY, ICE CREAM, PEANUT BUTTER PARTY, PEANUT BUTTER ICE CREAM, PEANUT BUTTER AND FUDGE SWIRLS, PEANUT BUTTER CUPS, UPC: 070640012411",
                "ndbno": "45110466",
                "ds": "BL"
            }
        ]
    }
}

我用AmCharts.stringToDate检查了JSON响应,这很好。我希望你能告诉我为什么,因为我对Golang很新。

我的结构:

type List struct {
    Q     string `json:"q,omitempty"`
    Sr    string `json:"sr,omitempty"`
    Ds    string `json:"ds,omitempty"`
    Start string `json:"start,omitempty"`
    End   string `json:"end,omitempty"`
    Total string `json:"total,omitempty"`
    Group string `json:"group,omitempty"`
    Sort  string `json:"sort,omitempty"`
    Item  []Item `json:"item,omitempty"`
}

type Item struct {
    Offset string `json:"offset,omitempty"`
    Group  string `json:"group,omitempty"` //food group to which the food belongs
    Name   string `json:"name,omitempty"`  //the food’s name
    Ndbno  string `json:"nbno,omitempty"`  //the food’s NDB Number
    Ds     string `json:"ds,omitempty"`    //Data source: BL=Branded Food Products or SR=Standard Release
}

代码:

func (sr *SearchRequest) fetch() {

    url := "https://api.nal.usda.gov/ndb/search/?" +
        "format=" + sr.format +
        "&q=" + sr.q +
        "&sort=" + sr.sort +
        "&max=" + strconv.FormatInt(sr.max, 10) +
        "&offset=" + strconv.FormatInt(sr.offset, 10) +
        "&api_key=" + sr.c.ApiKey

    r, err := http.Get(url)
    if err != nil {
        panic(err.Error())
    }
    defer r.Body.Close()

    b, err := ioutil.ReadAll(r.Body)
    if err != nil {
        panic(err.Error())
    }

    l := new(List)
    err = json.Unmarshal(b, &l)
    if err != nil {
        fmt.Println(err)
    }

    fmt.Println(l)

}

2 个答案:

答案 0 :(得分:2)

Go类型与JSON的结构不匹配。 JSON中还有一个对象级别。试试这个:

var v struct {
    List List
}
err := json.Unmarshal([]byte(data), &v)

某些字符串字段对应于JSON中的数字。使用数字类型(int,float64,...)声明这些字段。

playground example

答案 1 :(得分:0)

恕我直言,你的结构与你提供的JSON不匹配。尝试:

package main

import (

    "encoding/json"
    "fmt"
)

type MyItem struct {
    Q     string `json:"q,omitempty"`
    Sr    string `json:"sr,omitempty"`
    Ds    string `json:"ds,omitempty"`
    Start int `json:"start,omitempty"`
    End   int `json:"end,omitempty"`
    Total int `json:"total,omitempty"`
    Group string `json:"group,omitempty"`
    Sort  string `json:"sort,omitempty"`
    Item  []Item `json:"item,omitempty"`
}

type MyList struct {
    List MyItem `json:"list"`
}

type Item struct {
    Offset int `json:"offset,omitempty"`
    Group  string `json:"group,omitempty"` //food group to which the food belongs
    Name   string `json:"name,omitempty"`  //the food’s name
    Ndbno  string `json:"nbno,omitempty"`  //the food’s NDB Number
    Ds     string `json:"ds,omitempty"`    //Data source: BL=Branded Food Products or SR=Standard Release
}

var jsonStr = `{
    "list": {
        "q": "butter",
        "sr": "28",
        "ds": "any",
        "start": 0,
        "end": 50,
        "total": 4003,
        "group": "",
        "sort": "r",
        "item": [
            {
                "offset": 0,
                "group": "Branded Food Products Database",
                "name": "BLUE BUNNY, PEANUT BUTTER PANIC, ICE CREAM, POWERFUL PEANUT BUTTER ICE CREAM CHARGED WITH PEANUT BUTTER AND FUDGE SAUCES AND OVERLOADED WITH PEANUT BUTTER CUPS, UPC: 070640034086",
                "ndbno": "45011419",
                "ds": "BL"
            },
            {
                "offset": 1,
                "group": "Branded Food Products Database",
                "name": "BLUE BUNNY, ICE CREAM, PEANUT BUTTER PARTY, PEANUT BUTTER ICE CREAM, PEANUT BUTTER AND FUDGE SWIRLS, PEANUT BUTTER CUPS, UPC: 070640012411",
                "ndbno": "45110466",
                "ds": "BL"
            }]
}
}`


func main() {

b := jsonStr

    l := new(MyList)
    err := json.Unmarshal([]byte(b), &l)
    if err != nil {
        fmt.Println(err)
    }

    fmt.Println(l)
}

编辑:很难用%+ v读取println或printf的结果,所以这是spew.Dump(l)的结果(go get -u github.com/davecgh/go-spew/spew):< / p>

List: (main.MyItem) {
  Q: (string) (len=6) "butter",
  Sr: (string) (len=2) "28",
  Ds: (string) (len=3) "any",
  Start: (int) 0,
  End: (int) 50,
  Total: (int) 4003,
  Group: (string) "",
  Sort: (string) (len=1) "r",
  Item: ([]main.Item) (len=2 cap=4) {
   (main.Item) {
    Offset: (int) 0,
    Group: (string) (len=30) "Branded Food Products Database",
    Name: (string) (len=178) "BLUE BUNNY, PEANUT BUTTER PANIC, ICE CREAM, POWERFUL PEANUT BUTTER ICE CREAM CHARGED WITH PEANUT BUTTER AND FUDGE SAUCES AND OVERLOADED WITH PEANUT BUTTER CUPS, UPC: 070640034086",
    Ndbno: (string) "",
    Ds: (string) (len=2) "BL"
   },
   (main.Item) {
    Offset: (int) 1,
    Group: (string) (len=30) "Branded Food Products Database",
    Name: (string) (len=138) "BLUE BUNNY, ICE CREAM, PEANUT BUTTER PARTY, PEANUT BUTTER ICE CREAM, PEANUT BUTTER AND FUDGE SWIRLS, PEANUT BUTTER CUPS, UPC: 070640012411",
    Ndbno: (string) "",
    Ds: (string) (len=2) "BL"
   }
  }
 }
})