我正在使用 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 永远不会以正确的顺序获取其值。我从排序的 map 创建它。但这没有帮助。
var contentMap = make(map[string]Topic, sm.Len())
for _, key := range sm.Keys() {
contentMap[key.(string)] = first(sm.Get(key)).(Topic)
}
在某些时候,这张 map 似乎被重新创建,并且按键的顺序略有改变。 我想不出任何其他替代方案,因为 Gin 似乎只能正确序列化这个原始键值映射。来自 github.com/umpc/go-sortedmap 的排序映射根本没有序列化。
那么我如何保持这个原始( native ?)结构中键的顺序?或者我应该为 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)。否则找不到。
关于json - 如何创建一个可以由 Gin 序列化为 json 的排序键值映射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77815867/