我有一个地图对象,当使用json.Marshal(myMapObjct)Golang 对其进行序列化时,它会按字母顺序对键进行排序,这会导致数据处理方式出现问题。将 JSON 结构创建为字节切片后,保留键顺序很重要。是否可以以这种方式对其进行序列化,或者我是否需要为这种特定的边缘情况编写自己的序列化程序?
这是负责生成 JSON 结构的代码片段:
// serializedTraffic wraps around naturalTraffic and serializes map to string.
func serializedTraffic(payload string) (string, error) {
trafficMap := naturalTraffic(string(payload))
traffic, err := json.Marshal(trafficMap)
return string(traffic), err
}
// naturalTraffic obfuscates 'payload' into JSON-like structure.
func naturalTraffic(payload string) map[string]string {
// Decide on how many keys there will be in the JSON structure.
indexChar := 0
maxChars := 126
minChars := 16
var jsonObject = make(map[string]string)
// Build the JSON structure.
for indexChar < len(payload) {
rand.Seed(time.Now().UnixNano())
chunkSize := rand.Intn(maxChars-minChars) + minChars
if len(payload) < indexChar+chunkSize {
chunkSize = len(payload) - indexChar
}
key := randomPopularWord()
jsonObject[key] = base64.StdEncoding.EncodeToString([]byte(payload[indexChar : indexChar+chunkSize]))
indexChar += chunkSize
}
return jsonObject
}
繁花不似锦
相关分类