github.com/alexandrestein/gods@v1.0.1/maps/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  	"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  	for key, value := range m.m {
    22  		elements[utils.ToString(key)] = value
    23  	}
    24  	return json.Marshal(&elements)
    25  }
    26  
    27  // FromJSON populates list's elements from the input JSON representation.
    28  func (m *Map) FromJSON(data []byte) error {
    29  	elements := make(map[string]interface{})
    30  	err := json.Unmarshal(data, &elements)
    31  	if err == nil {
    32  		m.Clear()
    33  		for key, value := range elements {
    34  			m.m[key] = value
    35  		}
    36  	}
    37  	return err
    38  }