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 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
|
// 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 (
"encoding/json"
"github.com/mailru/easyjson/jlexer"
"reflect"
)
// Unmarshal parses the JSON-encoded object in 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, Unmarshal returns an ErrInvalidValue.
// If data is not a valid JSON or not a JSON object Unmarshal returns an ErrInvalidInput.
//
// Unmarshal 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.
// - Unmarshal only operates on JSON object inputs. It will reject all other types of input
// by returning ErrInvalidInput.
// - Unmarshal only operates on struct values. It will reject all other types of v by
// returning ErrInvalidValue.
// - Unmarshal supports three types of Mode values. Each mode is self documented and affects
// how Unmarshal behaves.
func Unmarshal(data []byte, v interface{}, options ...UnmarshalOption) (map[string]interface{}, error) {
if !isValidValue(v) {
return nil, ErrInvalidValue
}
opts := buildUnmarshalOptions(options)
useMultipleErrors := opts.mode == ModeAllowMultipleErrors || opts.mode == ModeFailOverToOriginalValue
d := &decoder{options: opts, lexer: &jlexer.Lexer{Data: data, UseMultipleErrors: useMultipleErrors}}
result := make(map[string]interface{})
if d.lexer.IsNull() {
d.lexer.Skip()
} else if !d.lexer.IsDelim('{') {
return nil, ErrInvalidInput
} else {
d.populateStruct(false, v, result)
}
d.lexer.Consumed()
if useMultipleErrors {
errors := d.lexer.GetNonFatalErrors()
if len(errors) == 0 {
return result, nil
}
return result, &MultipleLexerError{Errors: errors}
}
err := d.lexer.Error()
if err != nil {
return nil, err
}
return result, nil
}
type decoder struct {
options *unmarshalOptions
lexer *jlexer.Lexer
}
func (d *decoder) populateStruct(forcePopulate bool, structInstance interface{}, result map[string]interface{}) (interface{}, bool) {
doPopulate := !d.options.skipPopulateStruct || forcePopulate
var structValue reflect.Value
if doPopulate {
structValue = reflectStructValue(structInstance)
}
fields := mapStructFields(structInstance)
var clone map[string]interface{}
if d.options.mode == ModeFailOverToOriginalValue {
clone = make(map[string]interface{}, len(fields))
}
d.lexer.Delim('{')
for !d.lexer.IsDelim('}') {
key := d.lexer.UnsafeFieldName(false)
d.lexer.WantColon()
refInfo, exists := fields[key]
if exists {
value, isValidType := d.valueByReflectType(refInfo.t)
if isValidType {
if value != nil && doPopulate {
field := refInfo.field(structValue)
assignValue(field, value)
}
if !d.options.excludeKnownFieldsFromMap {
if result != nil {
result[key] = value
}
if clone != nil {
clone[key] = value
}
}
} else {
switch d.options.mode {
case ModeFailOnFirstError:
return nil, false
case ModeFailOverToOriginalValue:
if !forcePopulate {
result[key] = value
} else {
clone[key] = value
d.lexer.WantComma()
d.drainLexerMap(clone)
return clone, false
}
}
}
} else {
value := d.lexer.Interface()
if result != nil {
result[key] = value
}
if clone != nil {
clone[key] = value
}
}
d.lexer.WantComma()
}
d.lexer.Delim('}')
return structInstance, true
}
func (d *decoder) valueByReflectType(t reflect.Type) (interface{}, bool) {
if t.Implements(unmarshalerType) {
result := reflect.New(t.Elem()).Interface()
d.valueFromCustomUnmarshaler(result.(json.Unmarshaler))
return result, true
}
if reflect.PtrTo(t).Implements(unmarshalerType) {
value := reflect.New(t)
d.valueFromCustomUnmarshaler(value.Interface().(json.Unmarshaler))
return value.Elem().Interface(), true
}
kind := t.Kind()
if converter := primitiveConverters[kind]; converter != nil {
v := d.lexer.Interface()
if v == nil {
return nil, true
}
converted, ok := converter(v)
if !ok {
addUnexpectedTypeLexerError(d.lexer, t)
return v, false
}
return converted, true
}
switch kind {
case reflect.Slice:
return d.buildSlice(t)
case reflect.Array:
return d.buildArray(t)
case reflect.Map:
return d.buildMap(t)
case reflect.Struct:
value, valid := d.buildStruct(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 d.buildStruct(t.Elem())
}
value, valid := d.valueByReflectType(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
}
addUnsupportedTypeLexerError(d.lexer, t)
return nil, false
}
func (d *decoder) buildSlice(sliceType reflect.Type) (interface{}, bool) {
if d.lexer.IsNull() {
d.lexer.Skip()
return nil, true
}
if !d.lexer.IsDelim('[') {
addUnexpectedTypeLexerError(d.lexer, sliceType)
return d.lexer.Interface(), false
}
elemType := sliceType.Elem()
d.lexer.Delim('[')
var sliceValue reflect.Value
if !d.lexer.IsDelim(']') {
sliceValue = reflect.MakeSlice(sliceType, 0, 4)
} else {
sliceValue = reflect.MakeSlice(sliceType, 0, 0)
}
for !d.lexer.IsDelim(']') {
current, valid := d.valueByReflectType(elemType)
if !valid {
if d.options.mode != ModeFailOverToOriginalValue {
d.drainLexerArray(nil)
return nil, true
}
result := d.cloneReflectArray(sliceValue, -1)
result = append(result, current)
return d.drainLexerArray(result), true
}
sliceValue = reflect.Append(sliceValue, safeReflectValue(elemType, current))
d.lexer.WantComma()
}
d.lexer.Delim(']')
return sliceValue.Interface(), true
}
func (d *decoder) buildArray(arrayType reflect.Type) (interface{}, bool) {
if d.lexer.IsNull() {
d.lexer.Skip()
return nil, true
}
if !d.lexer.IsDelim('[') {
addUnexpectedTypeLexerError(d.lexer, arrayType)
return d.lexer.Interface(), false
}
elemType := arrayType.Elem()
arrayValue := reflect.New(arrayType).Elem()
d.lexer.Delim('[')
for i := 0; !d.lexer.IsDelim(']'); i++ {
current, valid := d.valueByReflectType(elemType)
if !valid {
if d.options.mode != ModeFailOverToOriginalValue {
d.drainLexerArray(nil)
return nil, true
}
result := d.cloneReflectArray(arrayValue, i)
result = append(result, current)
return d.drainLexerArray(result), true
}
if current != nil {
arrayValue.Index(i).Set(reflect.ValueOf(current))
}
d.lexer.WantComma()
}
d.lexer.Delim(']')
return arrayValue.Interface(), true
}
func (d *decoder) buildMap(mapType reflect.Type) (interface{}, bool) {
if d.lexer.IsNull() {
d.lexer.Skip()
return nil, true
}
if !d.lexer.IsDelim('{') {
addUnexpectedTypeLexerError(d.lexer, mapType)
return d.lexer.Interface(), false
}
d.lexer.Delim('{')
keyType := mapType.Key()
valueType := mapType.Elem()
mapValue := reflect.MakeMap(mapType)
for !d.lexer.IsDelim('}') {
key, valid := d.valueByReflectType(keyType)
if !valid {
if d.options.mode != ModeFailOverToOriginalValue {
d.lexer.WantColon()
d.lexer.Interface()
d.lexer.WantComma()
d.drainLexerMap(make(map[string]interface{}))
return nil, true
}
strKey, _ := key.(string)
d.lexer.WantColon()
value := d.lexer.Interface()
result := d.cloneReflectMap(mapValue)
result[strKey] = value
d.lexer.WantComma()
d.drainLexerMap(result)
return result, true
}
d.lexer.WantColon()
value, valid := d.valueByReflectType(valueType)
if !valid {
if d.options.mode != ModeFailOverToOriginalValue {
d.lexer.WantComma()
d.drainLexerMap(make(map[string]interface{}))
return nil, true
}
strKey, _ := key.(string)
result := d.cloneReflectMap(mapValue)
result[strKey] = value
d.lexer.WantComma()
d.drainLexerMap(result)
return result, true
}
mapValue.SetMapIndex(safeReflectValue(keyType, key), safeReflectValue(valueType, value))
d.lexer.WantComma()
}
d.lexer.Delim('}')
return mapValue.Interface(), true
}
func (d *decoder) buildStruct(structType reflect.Type) (interface{}, bool) {
if d.lexer.IsNull() {
d.lexer.Skip()
return nil, true
}
if !d.lexer.IsDelim('{') {
addUnexpectedTypeLexerError(d.lexer, structType)
return d.lexer.Interface(), false
}
value := reflect.New(structType).Interface()
handler, ok := asJSONDataHandler(value)
if !ok {
return d.populateStruct(true, value, nil)
}
data := make(map[string]interface{})
result, valid := d.populateStruct(true, value, data)
if !valid {
return result, false
}
err := handler(data)
if err != nil {
d.lexer.AddNonFatalError(err)
return result, false
}
return result, true
}
func (d *decoder) valueFromCustomUnmarshaler(unmarshaler json.Unmarshaler) {
data := d.lexer.Raw()
if !d.lexer.Ok() {
return
}
err := unmarshaler.UnmarshalJSON(data)
if err != nil {
d.lexer.AddNonFatalError(err)
}
}
func (d *decoder) cloneReflectArray(value reflect.Value, length int) []interface{} {
if length == -1 {
length = value.Len()
}
result := make([]interface{}, length)
for i := 0; i < length; i++ {
result[i] = value.Index(i).Interface()
}
return result
}
func (d *decoder) cloneReflectMap(mapValue reflect.Value) map[string]interface{} {
l := mapValue.Len()
result := make(map[string]interface{}, l)
for _, key := range mapValue.MapKeys() {
value := mapValue.MapIndex(key)
strKey, _ := key.Interface().(string)
result[strKey] = value.Interface()
}
return result
}
func (d *decoder) drainLexerArray(target []interface{}) interface{} {
d.lexer.WantComma()
for !d.lexer.IsDelim(']') {
current := d.lexer.Interface()
target = append(target, current)
d.lexer.WantComma()
}
d.lexer.Delim(']')
return target
}
func (d *decoder) drainLexerMap(target map[string]interface{}) {
for !d.lexer.IsDelim('}') {
key := d.lexer.String()
d.lexer.WantColon()
value := d.lexer.Interface()
target[key] = value
d.lexer.WantComma()
}
d.lexer.Delim('}')
}
|