/
serialization.go
103 lines (82 loc) · 1.96 KB
/
serialization.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
// 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"
"github.com/emirpasic/gods/containers"
"github.com/emirpasic/gods/utils"
)
func assertSerializationImplementation() {
var _ containers.JSONSerializer = (*Map)(nil)
var _ containers.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
}
utils.Sort(keys, byIndex)
m.Clear()
for _, key := range keys {
m.Put(key, elements[key.(string)])
}
return nil
}