-
Notifications
You must be signed in to change notification settings - Fork 14
/
json_serialization_helpers.go
54 lines (43 loc) · 1.48 KB
/
json_serialization_helpers.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
package jsonserialization
import (
"encoding/json"
"reflect"
absser "github.com/microsoft/kiota-abstractions-go/serialization"
)
// Unmarshal parses JSON-encoded data using a ParsableFactory and stores it in the value pointed to by model. To
// enable dirty tracking and better performance, set the DefaultParseNodeFactoryInstance for "application/json".
func Unmarshal[T absser.Parsable](data []byte, model *T, parser absser.ParsableFactory) error {
jpn, err := absser.DefaultParseNodeFactoryInstance.GetRootParseNode("application/json", data)
if err != nil {
if jpn, err = NewJsonParseNode(data); err != nil {
return err
}
}
v, err := jpn.GetObjectValue(parser)
if err != nil {
return err
}
if v != nil {
*model = v.(T)
} else {
// hand off to the std library to set model to its zero value
return json.Unmarshal(data, model)
}
return nil
}
// Marshal JSON-encodes a Parsable value. To enable dirty tracking and better performance, set the
// DefaultSerializationWriterFactoryInstance for "application/json".
func Marshal(v absser.Parsable) ([]byte, error) {
if vRef := reflect.ValueOf(v); !vRef.IsValid() || vRef.IsNil() {
return []byte("null"), nil
}
serializer, err := absser.DefaultSerializationWriterFactoryInstance.GetSerializationWriter("application/json")
if err != nil {
serializer = NewJsonSerializationWriter()
}
defer serializer.Close()
if err := v.Serialize(serializer); err != nil {
return nil, err
}
return serializer.GetSerializedContent()
}