github.com/mymmsc/gox@v1.3.33/util/linkedhashmap/serialization.go (about) 1 // Copyright (c) 2015, Emir Pasic. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package linkedhashmap 6 7 import ( 8 "bytes" 9 "encoding/json" 10 "github.com/mymmsc/gox/util" 11 ) 12 13 func assertSerializationImplementation() { 14 var _ util.JSONSerializer = (*Map)(nil) 15 var _ util.JSONDeserializer = (*Map)(nil) 16 } 17 18 // ToJSON outputs the JSON representation of map. 19 func (m *Map) ToJSON() ([]byte, error) { 20 var b []byte 21 buf := bytes.NewBuffer(b) 22 23 buf.WriteRune('{') 24 25 it := m.Iterator() 26 lastIndex := m.Size() - 1 27 index := 0 28 29 for it.Next() { 30 km, err := json.Marshal(it.Key()) 31 if err != nil { 32 return nil, err 33 } 34 buf.Write(km) 35 36 buf.WriteRune(':') 37 38 vm, err := json.Marshal(it.Value()) 39 if err != nil { 40 return nil, err 41 } 42 buf.Write(vm) 43 44 if index != lastIndex { 45 buf.WriteRune(',') 46 } 47 48 index++ 49 } 50 51 buf.WriteRune('}') 52 53 return buf.Bytes(), nil 54 } 55 56 // FromJSON populates map from the input JSON representation. 57 //func (m *Map) FromJSON(data []byte) error { 58 // elements := make(map[string]interface{}) 59 // err := json.Unmarshal(data, &elements) 60 // if err == nil { 61 // m.Clear() 62 // for key, value := range elements { 63 // m.Put(key, value) 64 // } 65 // } 66 // return err 67 //} 68 69 // FromJSON populates map from the input JSON representation. 70 func (m *Map) FromJSON(data []byte) error { 71 elements := make(map[string]interface{}) 72 err := json.Unmarshal(data, &elements) 73 if err != nil { 74 return err 75 } 76 77 index := make(map[string]int) 78 var keys []interface{} 79 for key := range elements { 80 keys = append(keys, key) 81 esc, _ := json.Marshal(key) 82 index[key] = bytes.Index(data, esc) 83 } 84 85 byIndex := func(a, b interface{}) int { 86 key1 := a.(string) 87 key2 := b.(string) 88 index1 := index[key1] 89 index2 := index[key2] 90 return index1 - index2 91 } 92 93 util.Sort(keys, byIndex) 94 95 m.Clear() 96 97 for _, key := range keys { 98 m.Put(key, elements[key.(string)]) 99 } 100 101 return nil 102 }