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