尝试从 JSON 响应中获取 "Total" 的值

Trying to get the value of "Total" from JSON response

响应:

{
“元”:{
“query_time”:0.039130201,
“分页”:{
“偏移量”:1345,
“限制”:5000,
“总数”:1345
},

结构:

类型 InLicense 结构 {
总 int16 json:"total,omitempty"
}

类型 OutLicense 结构 {
分页 []InLicense json:"pagination,omitempty"
}

键入 MetaLicense 结构 {
元 []OutLicense json:"meta,omitempty"
}

函数内的代码片段:

请求,错误 := http.NewRequest("GET", , nil)
如果错误!=无{
//处理错误
}

客户端 := &http.Client{}
resp, err := client.Do(req)
如果错误!=无{
log.Println("错误:", 错误)
}
推迟 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)
    }

}

}

在我 运行 这段代码之后,我得到以下错误: json:无法将对象解组到 []OutLicense

类型的 Go 结构字段 MetaLicense.meta

[]OutLicense 需要哪种类型才能正确解组?我无法以其他方式打印它,但它使用 {} 打印并且 Strings.Trim 将不起作用。

您应该只使用具有实际类型的简单字段声明,而不是如下所示的 [] 类型:

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

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

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

我稍微简化了解析,只是使用了 json.Unmarshal() 函数。

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

这是我使用的类型

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

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

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

正如所写,您提供的 JSON 有一个额外的 ,,这使得您的 json 无法解析(假设您也添加了缺失的 }

您的 JSON 中没有列表。列表用 [] 符号表示。为了使您的类型起作用,您的 JSON 必须如下所示:

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