登录
首页 >  Golang >  Go问答

将嵌套结构化解析 JSON

来源:stackoverflow

时间:2024-02-08 15:18:22 230浏览 收藏

来到golang学习网的大家,相信都是编程学习爱好者,希望在这里学习Golang相关编程知识。下面本篇文章就来带大家聊聊《将嵌套结构化解析 JSON》,介绍一下,希望对大家的知识积累有所帮助,助力实战开发!

问题内容

type apiresponse struct {
    results []result    `json:"results,omitempty"`
    paging  paging
}
type result struct {
    id string `json:"id"`,
    name string `json:"name"`,
}
type paging struct {
    count    int    `json:"count"`
    previous string `json:"previous"`
    next     string `json:"next"`
}

func  get(ctx context.context) apiresponse[t] {
    results := apiresponse{}
    rc, err := r.dorequest(ctx, req)
    if rc != nil {
        defer rc.close()
    }
    err = json.newdecoder(rc).decode(&results)
    return results
}

示例 json 如下所示:

{
    "count": 70,
    "next": "https://api?page=2",
    "previous": null,
    "results": [
        {
            "id": 588,
            "name": "Tesco",
            }...

我希望将其解码为 apiresponse 形式的结构,其中分页元素是子结构,就像结果一样。但是,在示例 json 中,分页方面没有父 json 标签。它如何被解码成它自己的单独的结构?

目前,如果我将 count、next 和 previous 提升到 apiresponse 中,它们就会出现,但当它们是子结构时不会出现。


正确答案


将您的 paging 结构直接嵌入到 apiresponse 中,如下所示:

type APIResponse struct {
    Results []Result    `json:"results,omitempty"`
    Paging
}
type Result struct {
    Id string `json:"id"`,
    Name string `json:"name"`,
}
type Paging struct {
    Count    int    `json:"count"`
    Previous string `json:"previous"`
    Next     string `json:"next"`
}

这样它将按照该结构中定义的方式工作。您可以通过两种方式访问​​其字段:

  1. 直接: apiresponse.count
  2. 间接: apiresponse.paging.count

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《将嵌套结构化解析 JSON》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>