-
Notifications
You must be signed in to change notification settings - Fork 1
/
json.go
67 lines (56 loc) · 1.35 KB
/
json.go
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package gosenml
import (
"encoding/json"
)
// JSONEncoder encodes SenML messages to JSON
type JSONEncoder struct{}
// NewJSONEncoder returns a new JSONEncoder
func NewJSONEncoder() *JSONEncoder {
return &JSONEncoder{}
}
// EncodeMessage encodes a SenML message to JSON
func (je *JSONEncoder) EncodeMessage(m *Message) ([]byte, error) {
if err := m.Validate(); err != nil {
return []byte{}, err
}
b, err := json.Marshal(m)
if err != nil {
return []byte{}, err
}
return b, nil
}
// EncodeEntry encodes a SenML entry to JSON
func (je *JSONEncoder) EncodeEntry(e *Entry) ([]byte, error) {
b, err := json.Marshal(e)
if err != nil {
return []byte{}, err
}
return b, nil
}
// JSONDecoder decodes SenML messages from JSON
type JSONDecoder struct{}
// NewJSONDecoder returns a new JSONDecoder
func NewJSONDecoder() *JSONDecoder {
return &JSONDecoder{}
}
// DecodeMessage decodes a SenML messages from JSON
func (jd *JSONDecoder) DecodeMessage(data []byte) (Message, error) {
m := Message{}
err := json.Unmarshal(data, &m)
if err != nil {
return Message{}, err
}
if err = m.Validate(); err != nil {
return m, err
}
return m, nil
}
// DecodeEntry decodes a SenML entry from JSON
func (jd *JSONDecoder) DecodeEntry(data []byte) (Entry, error) {
e := Entry{}
err := json.Unmarshal(data, &e)
if err != nil {
return Entry{}, err
}
return e, nil
}