-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathunmarshal_from_json_map.go
295 lines (281 loc) · 8.62 KB
/
unmarshal_from_json_map.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
// Copyright 2022 PerimeterX. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package marshmallow
import (
"reflect"
)
// UnmarshalerFromJSONMap is the interface implemented by types
// that can unmarshal a JSON description of themselves.
// In case you want to implement custom unmarshalling, json.Unmarshaler only supports
// receiving the data as []byte. However, while unmarshalling from JSON map,
// the data is not available as a raw []byte and converting to it will significantly
// hurt performance. Thus, if you wish to implement a custom unmarshalling on a type
// that is being unmarshalled from a JSON map, you need to implement
// UnmarshalerFromJSONMap interface.
type UnmarshalerFromJSONMap interface {
UnmarshalJSONFromMap(data interface{}) error
}
// UnmarshalFromJSONMap parses the JSON map data and stores the values
// in the struct pointed to by v and in the returned map.
// If v is nil or not a pointer to a struct, UnmarshalFromJSONMap returns an ErrInvalidValue.
//
// UnmarshalFromJSONMap follows the rules of json.Unmarshal with the following exceptions:
// - All input fields are stored in the resulting map, including fields that do not exist in the
// struct pointed by v.
// - UnmarshalFromJSONMap receive a JSON map instead of raw bytes. The given input map is assumed
// to be a JSON map, meaning it should only contain the following types: bool, string, float64,
// []interface, and map[string]interface{}. Other types will cause decoding to return unexpected results.
// - UnmarshalFromJSONMap only operates on struct values. It will reject all other types of v by
// returning ErrInvalidValue.
// - UnmarshalFromJSONMap supports three types of Mode values. Each mode is self documented and affects
// how UnmarshalFromJSONMap behaves.
func UnmarshalFromJSONMap(data map[string]interface{}, v interface{}, options ...UnmarshalOption) (map[string]interface{}, error) {
if !isValidValue(v) {
return nil, ErrInvalidValue
}
opts := buildUnmarshalOptions(options)
d := &mapDecoder{options: opts}
result := make(map[string]interface{})
if data != nil {
d.populateStruct(false, nil, data, v, result)
}
if opts.mode == ModeAllowMultipleErrors || opts.mode == ModeFailOverToOriginalValue {
if len(d.errs) == 0 {
return result, nil
}
return result, &MultipleError{Errors: d.errs}
}
if d.err != nil {
return nil, d.err
}
return result, nil
}
var unmarshalerFromJSONMapType = reflect.TypeOf((*UnmarshalerFromJSONMap)(nil)).Elem()
type mapDecoder struct {
options *unmarshalOptions
err error
errs []error
}
func (m *mapDecoder) populateStruct(forcePopulate bool, path []string, data map[string]interface{}, structInstance interface{}, result map[string]interface{}) (interface{}, bool) {
doPopulate := !m.options.skipPopulateStruct || forcePopulate
var structValue reflect.Value
if doPopulate {
structValue = reflectStructValue(structInstance)
}
fields := mapStructFields(structInstance)
for key, inputValue := range data {
refInfo, exists := fields[key]
if exists {
value, isValidType := m.valueByReflectType(append(path, key), inputValue, refInfo.t)
if isValidType {
if value != nil && doPopulate {
field := refInfo.field(structValue)
assignValue(field, value)
}
if !m.options.excludeKnownFieldsFromMap {
if result != nil {
result[key] = value
}
}
} else {
switch m.options.mode {
case ModeFailOnFirstError:
return nil, false
case ModeFailOverToOriginalValue:
if !forcePopulate {
result[key] = value
} else {
return data, false
}
}
}
} else {
if result != nil {
result[key] = inputValue
}
}
}
return structInstance, true
}
func (m *mapDecoder) valueByReflectType(path []string, v interface{}, t reflect.Type) (interface{}, bool) {
if t.Implements(unmarshalerFromJSONMapType) {
result := reflect.New(t.Elem()).Interface()
m.valueFromCustomUnmarshaler(v, result.(UnmarshalerFromJSONMap))
return result, true
}
if reflect.PtrTo(t).Implements(unmarshalerFromJSONMapType) {
value := reflect.New(t)
m.valueFromCustomUnmarshaler(v, value.Interface().(UnmarshalerFromJSONMap))
return value.Elem().Interface(), true
}
kind := t.Kind()
if converter := primitiveConverters[kind]; converter != nil {
if v == nil {
return nil, true
}
converted, ok := converter(v)
if !ok {
m.addError(newUnexpectedTypeParseError(t, path))
return v, false
}
return converted, true
}
switch kind {
case reflect.Slice:
return m.buildSlice(path, v, t)
case reflect.Array:
return m.buildArray(path, v, t)
case reflect.Map:
return m.buildMap(path, v, t)
case reflect.Struct:
value, valid := m.buildStruct(path, v, t)
if value == nil {
return nil, valid
}
if !valid {
return value, false
}
return reflect.ValueOf(value).Elem().Interface(), valid
case reflect.Ptr:
if t.Elem().Kind() == reflect.Struct {
return m.buildStruct(path, v, t.Elem())
}
value, valid := m.valueByReflectType(path, v, t.Elem())
if value == nil {
return nil, valid
}
if !valid {
return value, false
}
result := reflect.New(reflect.TypeOf(value))
result.Elem().Set(reflect.ValueOf(value))
return result.Interface(), valid
}
m.addError(newUnsupportedTypeParseError(t, path))
return nil, false
}
func (m *mapDecoder) buildSlice(path []string, v interface{}, sliceType reflect.Type) (interface{}, bool) {
if v == nil {
return nil, true
}
arr, ok := v.([]interface{})
if !ok {
m.addError(newUnexpectedTypeParseError(sliceType, path))
return v, false
}
elemType := sliceType.Elem()
var sliceValue reflect.Value
if len(arr) > 0 {
sliceValue = reflect.MakeSlice(sliceType, 0, 4)
} else {
sliceValue = reflect.MakeSlice(sliceType, 0, 0)
}
for _, element := range arr {
current, valid := m.valueByReflectType(path, element, elemType)
if !valid {
if m.options.mode != ModeFailOverToOriginalValue {
return nil, true
}
return v, true
}
sliceValue = reflect.Append(sliceValue, safeReflectValue(elemType, current))
}
return sliceValue.Interface(), true
}
func (m *mapDecoder) buildArray(path []string, v interface{}, arrayType reflect.Type) (interface{}, bool) {
if v == nil {
return nil, true
}
arr, ok := v.([]interface{})
if !ok {
m.addError(newUnexpectedTypeParseError(arrayType, path))
return v, false
}
elemType := arrayType.Elem()
arrayValue := reflect.New(arrayType).Elem()
for i, element := range arr {
current, valid := m.valueByReflectType(path, element, elemType)
if !valid {
if m.options.mode != ModeFailOverToOriginalValue {
return nil, true
}
return v, true
}
if current != nil {
arrayValue.Index(i).Set(reflect.ValueOf(current))
}
}
return arrayValue.Interface(), true
}
func (m *mapDecoder) buildMap(path []string, v interface{}, mapType reflect.Type) (interface{}, bool) {
if v == nil {
return nil, true
}
mp, ok := v.(map[string]interface{})
if !ok {
m.addError(newUnexpectedTypeParseError(mapType, path))
return v, false
}
keyType := mapType.Key()
valueType := mapType.Elem()
mapValue := reflect.MakeMap(mapType)
for inputKey, inputValue := range mp {
keyPath := append(path, inputKey)
key, valid := m.valueByReflectType(keyPath, inputKey, keyType)
if !valid {
if m.options.mode != ModeFailOverToOriginalValue {
return nil, true
}
return v, true
}
value, valid := m.valueByReflectType(keyPath, inputValue, valueType)
if !valid {
if m.options.mode != ModeFailOverToOriginalValue {
return nil, true
}
return v, true
}
mapValue.SetMapIndex(safeReflectValue(keyType, key), safeReflectValue(valueType, value))
}
return mapValue.Interface(), true
}
func (m *mapDecoder) buildStruct(path []string, v interface{}, structType reflect.Type) (interface{}, bool) {
if v == nil {
return nil, true
}
mp, ok := v.(map[string]interface{})
if !ok {
m.addError(newUnexpectedTypeParseError(structType, path))
return v, false
}
value := reflect.New(structType).Interface()
handler, ok := asJSONDataHandler(value)
if !ok {
return m.populateStruct(true, path, mp, value, nil)
}
data := make(map[string]interface{})
result, valid := m.populateStruct(true, path, mp, value, data)
if !valid {
return result, false
}
err := handler(data)
if err != nil {
m.addError(err)
return result, false
}
return result, true
}
func (m *mapDecoder) valueFromCustomUnmarshaler(data interface{}, unmarshaler UnmarshalerFromJSONMap) {
err := unmarshaler.UnmarshalJSONFromMap(data)
if err != nil {
m.addError(err)
}
}
func (m *mapDecoder) addError(err error) {
if m.options.mode == ModeFailOnFirstError {
m.err = err
} else {
m.errs = append(m.errs, err)
}
}