我正在使用Gin创建一个REST API.我try 创建的响应是一个键值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[字符串]主题永远不会以正确的顺序获取其值.我从一个已排序的 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的排序映射根本没有序列化.

那么,如何在这个原始(原生?) struct 中保持键的顺序呢?或者我应该为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(not *SortedMapWrapper).否则它不会被发现.

Json相关问答推荐

将嵌套的json中的字符串强制转换为数字

如何使用表键名称GROUP_BY

织女星-没有循环的动画条形图第二部分(实际上是织女星)

将PNG图像保存为Python中的JSON文件

如何获取 JSON 对象字段值和同一 JSON 对象的下一个数组中的字段值?

展平多个数组以保持顺序

使用jq根据对象中键的值查找对象

jq可以在两个JSON对象列表中依次添加对象吗?

通过 xslt 将内部 json 转换为 xml 时遇到问题

如何配置spring mvc 3在json响应中不返回null对象?

如何使用 CORS 实现 JavaScript Google Places API 请求

JSON RPC - 什么是id?

在 Bash 中访问 JSON 对象 - 关联数组/列表/另一个模型

在 JSON 编码的 HTML5 数据属性中转义/编码单引号

如何自动修复无效的 JSON 字符串?

在 Android 中使用带有 post 参数的 HttpClient 和 HttpPost

使用 Codable 序列化为 JSON 时的 Swift 字符串转义

SCRIPT5009:JSON未定义

添加json文件注释

如何遍历 JSON 中的条目?