如何建立一個可以由 Gin 序列化為 json 的排序鍵值映射?
在使用Go語言開發網頁應用程式時,經常會涉及將資料序列化為JSON格式。而對於排序鍵值映射的序列化,我們可以藉助Gin框架和Golang中的map資料結構來實現。在本文中,php小編香蕉將為您詳細介紹如何創建一個可以由Gin序列化為JSON的排序鍵值映射,讓您的Web應用更加靈活和高效。讓我們一起來看看具體的實作方法吧!
問題內容
我正在使用 Gin 建立 REST API。我嘗試創建的回應是一個鍵值 json 映射,例如:
"content": { "1.4.5.": { "id": "1.4.5.", "content": "some content", "title": "title" }, "1.4.6.": { "id": "1.4.6.", "content": "another content", "title": "another title" },
我使用的資料模型是:
type TopicBundle struct { ... Content map[string]Topic `json:"content"` }
並且它被正確序列化為 json:
c.JSON(200, topicBundle)
幾乎。
map[string]Topic 永遠不會以正確的順序取得其值。我從排序的地圖創建它。但這沒有幫助。
var contentMap = make(map[string]Topic, sm.Len()) for _, key := range sm.Keys() { contentMap[key.(string)] = first(sm.Get(key)).(Topic) }
在某些時候,這張地圖似乎被重新創建,並且按鍵的順序略有改變。 我想不出任何其他替代方案,因為 Gin 似乎只能正確序列化這個原始鍵值映射。來自 github.com/umpc/go-sortedmap 的排序映射根本沒有序列化。
那麼我如何保持這個原始(本機?)結構中鍵的順序?或者我應該為 Gin 編寫一個自訂序列化器?
我嘗試在網路上找到解決方案。
解決方法
我的解決方案是圍繞sortedmap.SortedMap 編寫一個包裝器,並為此包裝器編寫一個自訂MarshalJSON# :
type TopicBundle struct { Content SortedMapWrapper `json:"content"` } type SortedMapWrapper struct { topics *sortedmap.SortedMap } func (wrapper SortedMapWrapper) MarshalJSON() ([]byte, error) { var sb strings.Builder var counter = 0 sb.WriteString("{") for _, key := range wrapper.topics.Keys() { sb.WriteString("\"") sb.WriteString(key.(string)) sb.WriteString("\":") sb.Write(first(json.Marshal(first(wrapper.topics.Get(key))))) counter += 1 if counter < wrapper.topics.Len() { sb.WriteString(",") } } sb.WriteString("}") return []byte(sb.String()), nil } func loadTopic(c *gin.Context) { var contentMap = sortedmap.New(1, comparisonFunc) contentMap.Insert("val1", Topic{"val1", "val2", "val3"}) contentMap.Insert("val33", Topic{"val1", "val2", "val3"}) var topicBundle = TopicBundle{} topicBundle.Content = SortedMapWrapper{contentMap} c.JSON(200, topicBundle) }
請注意,MarshalJSON 的定義應使用 SortedMapWrapper(而不是 *SortedMapWrapper)。否則找不到。
以上是如何建立一個可以由 Gin 序列化為 json 的排序鍵值映射?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)