程序开发 · 2024年1月30日

go中json序列化后的Anonymus结构

当前位置: > > > > go中json序列化后的Anonymus结构

来源:stackoverflow
2024-04-27 14:15:37
0浏览
收藏

来到的大家,相信都是编程学习爱好者,希望在这里学习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"`
}

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