登录
首页 >  Golang >  Go问答

go中json序列化后的Anonymus结构

来源:stackoverflow

时间:2024-04-27 14:15:37 270浏览 收藏

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

问题内容

我想实现这样的输出json格式

{
    "2019-07-22": {
        "something": {
            "type": "entry",
            "id": 1766617,
        },
        "something2": {
            "type": "entry",
            "id": 1766617,
        },
    },
    "2019-07-23": {
        "something": {
            "type": "entry",
            "id": 1766618,
        },
        "something2": {
            "type": "entry",
            "id": 1766620,
        },
    },
}

到目前为止,我已将这些数据分成 3 个结构:

type response struct {
    days map[string]day
}

type day struct {
    entries map[string]entry
}

type entry struct {
    type            string `json:"type"`
    id              int    `json:"id"`
}

序列化为 json 后,我的结构包含字段名称和嵌套 json 对象,这是错误的:

{
    "Days": {
        "2019-07-22": {
            "Entries": {
                "something": {
                    "type": "ENTRY",
                    "id": 1766617
                },
                "something2": {
                    "type": "ENTRY",
                    "id": 1766617
                }
            }
        }
    }
}

是否可以跳过 response:daysday:entries 字段中的这些字段名称?我不会将 json 反序列化为结构,所以唯一的问题是序列化。由于 bc 破坏,我无法更改 json 结构。


解决方案


要实现您想要的 json,您的 response 类型应该是地图的地图。

type Response map[string]map[string]Entry

type Entry struct {
    Type string `json:"type"`
    Id   int    `json:"id"`
}

https://play.golang.com/p/4GBEZi_TS9m

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

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