gitee.com/quant1x/gox@v1.21.2/util/hashmap/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 hashmap 6 7 import ( 8 "encoding/json" 9 "gitee.com/quant1x/gox/util/internal" 10 ) 11 12 func assertSerializationImplementation() { 13 var _ internal.JSONSerializer = (*Map)(nil) 14 var _ internal.JSONDeserializer = (*Map)(nil) 15 } 16 17 // ToJSON outputs the JSON representation of the map. 18 func (m *Map) ToJSON() ([]byte, error) { 19 elements := make(map[string]interface{}) 20 for key, value := range m.m { 21 elements[internal.ToString(key)] = value 22 } 23 return json.Marshal(&elements) 24 } 25 26 // FromJSON populates the map from the input JSON representation. 27 func (m *Map) FromJSON(data []byte) error { 28 elements := make(map[string]interface{}) 29 err := json.Unmarshal(data, &elements) 30 if err == nil { 31 m.Clear() 32 for key, value := range elements { 33 m.m[key] = value 34 } 35 } 36 return err 37 }