2 Star 2 Fork 9

王布衣/gox

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
serialization.go 1.92 KB
一键复制 编辑 原始数据 按行查看 历史
王布衣 提交于 2023-06-07 20:08 . 修订部分util工具库
// Copyright (c) 2015, Emir Pasic. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package linkedhashmap
import (
"bytes"
"encoding/json"
"gitee.com/quant1x/gox/util/internal"
)
func assertSerializationImplementation() {
var _ internal.JSONSerializer = (*Map)(nil)
var _ internal.JSONDeserializer = (*Map)(nil)
}
// ToJSON outputs the JSON representation of map.
func (m *Map) ToJSON() ([]byte, error) {
var b []byte
buf := bytes.NewBuffer(b)
buf.WriteRune('{')
it := m.Iterator()
lastIndex := m.Size() - 1
index := 0
for it.Next() {
km, err := json.Marshal(it.Key())
if err != nil {
return nil, err
}
buf.Write(km)
buf.WriteRune(':')
vm, err := json.Marshal(it.Value())
if err != nil {
return nil, err
}
buf.Write(vm)
if index != lastIndex {
buf.WriteRune(',')
}
index++
}
buf.WriteRune('}')
return buf.Bytes(), nil
}
// FromJSON populates map from the input JSON representation.
//func (m *Map) FromJSON(data []byte) error {
// elements := make(map[string]interface{})
// err := json.Unmarshal(data, &elements)
// if err == nil {
// m.Clear()
// for key, value := range elements {
// m.Put(key, value)
// }
// }
// return err
//}
// FromJSON populates map from the input JSON representation.
func (m *Map) FromJSON(data []byte) error {
elements := make(map[string]interface{})
err := json.Unmarshal(data, &elements)
if err != nil {
return err
}
index := make(map[string]int)
var keys []interface{}
for key := range elements {
keys = append(keys, key)
esc, _ := json.Marshal(key)
index[key] = bytes.Index(data, esc)
}
byIndex := func(a, b interface{}) int {
key1 := a.(string)
key2 := b.(string)
index1 := index[key1]
index2 := index[key2]
return index1 - index2
}
internal.Sort(keys, byIndex)
m.Clear()
for _, key := range keys {
m.Put(key, elements[key.(string)])
}
return nil
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/quant1x/gox.git
git@gitee.com:quant1x/gox.git
quant1x
gox
gox
v1.13.3

搜索帮助