douweibeng5219
2019-07-24 08:40
浏览 164

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.

图片转代码服务由CSDN问答提供 功能建议

我想为输出json实现这种格式

  {\  n“ 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响应结构{
 Days map [string] Day 
} 
 
type Day struct {
 Entry map [string] Entry 
} 
 
type Entry struct {
 type string`json:“ type  “`
 Id int`json:” id“`
} 
   
 
 

序列化为json后,我具有带有字段名和嵌套json对象的结构 是错误的:

  {
“天”:{
“ 2019-07-22”:{
“条目”:{
“某物”:{  
“ type”:“ ENTRY”,
“ id”:1766617 
},
“ something2”:{
“ type”:“ ENTRY”,
“ id”:1766617 
} 
  } 
} 
} 
} 
   
 
 

是否有可能跳过 Response:Days Day:条目字段? 我不会将json反序列化为结构,因此唯一的问题是序列化。 由于BC中断,我无法更改json结构。

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

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

    打赏 评论

相关推荐 更多相似问题