forked from golangwrt/libubox
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jsonobject.go
59 lines (53 loc) · 1.25 KB
/
jsonobject.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
package libubox
import (
"encoding/json"
"fmt"
"reflect"
)
// JsonObject
type JSONObject struct {
Value interface {}
// underlying struct type
T reflect.Type
}
// NewJSONObject create a new json object, then
// bind the type/value with i
func NewJSONObject(i interface{}) (*JSONObject, error) {
obj, err := NewJSONObjectWith(reflect.TypeOf(i))
if err != nil {
return nil, err
}
obj.Value = i
return obj, nil
}
// NewJSONObjectWith create a new json object, then
// bind the object with concrete struct type of i
func NewJSONObjectWith(t reflect.Type) (*JSONObject, error) {
if t == nil {
return nil, fmt.Errorf("nil type")
}
for t.Kind() == reflect.Ptr {
t = t.Elem()
}
if t.Kind() != reflect.Struct {
return nil, fmt.Errorf("parameter type is %s, require struct", t.Kind().String())
}
return &JSONObject{
T: t,
}, nil
}
func (obj *JSONObject) UnmarshalBlobAttr(attr *BlobAttr) error {
return obj.UnmarshalJSON([]byte(attr.FormatJSON(true)))
}
func (obj *JSONObject) UnmarshalJSON(data []byte) error {
val := reflect.New(obj.T)
err := json.Unmarshal(data, val.Interface())
if err != nil {
return err
}
obj.Value = val.Interface()
return nil
}
func (obj *JSONObject) MarshalJSON() ([]byte, error) {
return json.Marshal(obj.Value)
}