douweibeng5219 2019-07-24 08:40
浏览 174
已采纳

Go中的json序列化后的匿名结构

I want achieve such format for output 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,
        },
    },
}

So far I've split those data into 3 structs:

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"`
}

After serialize into json I have structure with field names and nested json objects which is wrong:

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

Is there possibility to skip those field names in Response:Days and Day:Entries fields? I will not deserialize json into structs so only problem is serialization. I can't change json structure because of BC breakes.

  • 写回答

1条回答 默认 最新

  • duanhu2414 2019-07-24 11:29
    关注

    To achieve the json you want your Response type should be a map of maps.

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号