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
5package treebidimap
6
7import (
8	"encoding/json"
9	"github.com/emirpasic/gods/containers"
10	"github.com/emirpasic/gods/utils"
11)
12
13func assertSerializationImplementation() {
14	var _ containers.JSONSerializer = (*Map)(nil)
15	var _ containers.JSONDeserializer = (*Map)(nil)
16}
17
18// ToJSON outputs the JSON representation of the map.
19func (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 the map from the input JSON representation.
29func (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}
40