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