-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmap_value.go
More file actions
43 lines (37 loc) · 955 Bytes
/
map_value.go
File metadata and controls
43 lines (37 loc) · 955 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package orderedmap
import (
"encoding/json"
"fmt"
"reflect"
)
// Entry represents a map value entry.
type Entry struct {
index uint64
Value any
}
// UnmarshalJSON implements the json.Unmarshaler interface.
func (s *Entry) UnmarshalJSON(b []byte) error {
s.index = nextSequence()
if err := json.Unmarshal(b, &s.Value); err != nil {
return fmt.Errorf("unmarshalling entry: %w", err)
}
if s.Value != nil {
valueKind := reflect.TypeOf(s.Value).Kind()
if valueKind == reflect.Map { // force values of type map to be of ordered map as well
var m Map
if err := json.Unmarshal(b, &m); err != nil {
return fmt.Errorf("unmarshalling json entry into map: %w", err)
}
s.Value = m
}
}
return nil
}
// MarshalJSON implements the json.Marshaler interface.
func (s *Entry) MarshalJSON() ([]byte, error) {
b, err := json.Marshal(s.Value)
if err != nil {
return nil, fmt.Errorf("marshalling entry: %w", err)
}
return b, nil
}