0
votes

Response:

{
"meta": {
"query_time": 0.039130201,
"pagination": {
"offset": 1345,
"limit": 5000,
"total": 1345
},

Structs:

type InLicense struct {
Total int16 json:"total,omitempty"
}

type OutLicense struct {
Pagination []InLicense json:"pagination,omitempty"
}

type MetaLicense struct {
Meta []OutLicense json:"meta,omitempty"
}

Code snip inside function:

req, err := http.NewRequest("GET", , nil)
if err != nil {
//handle error
}

client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Println("Error: ", err)
}
defer resp.Body.Close()
val := &MetaLicense{}

err = json.NewDecoder(resp.Body).Decode(&val)
if err != nil {
    log.Fatal(err)
}

for _, s := range val.Meta {
    for _, a := range s.Pagination {
        fmt.Println(a.Total)
    }

}

}

After I run this code I get the following error: json: cannot unmarshal object into Go struct field MetaLicense.meta of type []OutLicense

Which type would []OutLicense need to be in order for this to be unmarshaled correctly? I cant print it another way, but it prints with the {} and Strings.Trim will not work.

2

2 Answers

1
votes

You should use just a simple field declaration with actual type, not a [] of the type as it is done below:

type InLicense struct {
    Total int16 json:"total,omitempty"
}

type OutLicense struct {
     Pagination InLicense json:"pagination,omitempty"
}

type MetaLicense struct {
    Meta OutLicense json:"meta,omitempty"
}
1
votes

I simplified the parsing a bit and just used the json.Unmarshal() function instead.

raw := "{\n  \"meta\": {\n    \"query_time\": 0.039130201,\n    \"pagination\": {\n      \"offset\": 1345,\n      \"limit\": 5000,\n      \"total\": 1345\n    }\n  }\n}"

parsed := &MetaLicense{}
err := json.Unmarshal([]byte(raw), parsed)
if err != nil {
    log.Fatal(err)
}

fmt.Println(parsed.Meta.Pagination.Total) // Prints: 1345

Here's the types I used

type InLicense struct {
    Total int16 `json:"total,omitempty"`
}

type OutLicense struct {
    Pagination InLicense `json:"pagination,omitempty"`
}

type MetaLicense struct {
    Meta OutLicense `json:"meta,omitempty"`
}

As written your provided JSON has a extra , which makes your json unparsable (assuming you add the missing }'s too.

There are no lists in your JSON. Lists are denoted with the [] symbols. For your types to work it, your JSON would have to look like this:

{
  "meta": [{
    "query_time": 0.039130201,
    "pagination": [{
      "offset": 1345,
      "limit": 5000,
      "total": 1345
    }]
  }]
}