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