使用Gin将键值映射序列化为JSON形式的排序方法介绍
时间:2024-02-05
浏览:382
作者:佚名
今日不肯埋头,明日何以抬头!每日一句努力自己的话哈哈~哈喽,今天我将给大家带来一篇《使用Gin将键值映射序列化为JSON形式的排序方法介绍》,主要内容是讲解等等,感兴趣的朋友可以收藏或者有更好的建议在评论提出,我都会认真看的!大家一起进步,一起学习!
问题内容我正在使用 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形式的排序方法介绍》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
12.01
热门专题
