
在使用Go语言开发Web应用时,经常会涉及到将数据序列化为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中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号