-
Notifications
You must be signed in to change notification settings - Fork 0
/
json.go
executable file
·579 lines (469 loc) · 12.6 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
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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
// Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.
package utils
import (
"bytes"
"encoding/json"
"fmt"
"math/big"
"reflect"
"strings"
"time"
"unsafe"
"github.com/speakeasy-sdks/test-sample-sdk/pkg/types"
"github.com/ericlagergren/decimal"
)
func MarshalJSON(v interface{}, tag reflect.StructTag, topLevel bool) ([]byte, error) {
typ, val := dereferencePointers(reflect.TypeOf(v), reflect.ValueOf(v))
switch {
case isModelType(typ):
if topLevel {
return json.Marshal(v)
}
if isNil(typ, val) {
return []byte("null"), nil
}
out := map[string]json.RawMessage{}
for i := 0; i < typ.NumField(); i++ {
field := typ.Field(i)
fieldVal := val.Field(i)
fieldName := field.Name
omitEmpty := false
jsonTag := field.Tag.Get("json")
if jsonTag != "" {
for _, tag := range strings.Split(jsonTag, ",") {
if tag == "omitempty" {
omitEmpty = true
} else {
fieldName = tag
}
}
}
if isNil(field.Type, fieldVal) {
if omitEmpty {
continue
}
}
if !field.IsExported() && field.Tag.Get("const") == "" {
continue
}
additionalProperties := field.Tag.Get("additionalProperties")
if fieldName == "-" && additionalProperties == "" {
continue
}
if additionalProperties == "true" {
if field.Type.Kind() != reflect.Map {
return nil, fmt.Errorf("additionalProperties must be a map")
}
for _, key := range fieldVal.MapKeys() {
r, err := marshalValue(fieldVal.MapIndex(key).Interface(), field.Tag)
if err != nil {
return nil, err
}
out[key.String()] = r
}
continue
}
var fv interface{}
if field.IsExported() {
fv = fieldVal.Interface()
} else {
pt := reflect.New(typ).Elem()
pt.Set(val)
pf := pt.Field(i)
fv = reflect.NewAt(pf.Type(), unsafe.Pointer(pf.UnsafeAddr())).Elem().Interface()
}
r, err := marshalValue(fv, field.Tag)
if err != nil {
return nil, err
}
out[fieldName] = r
}
return json.Marshal(out)
default:
return marshalValue(v, tag)
}
}
func UnmarshalJSON(b []byte, v interface{}, tag reflect.StructTag, topLevel bool, disallowUnknownFields bool) error {
if reflect.TypeOf(v).Kind() != reflect.Ptr {
return fmt.Errorf("v must be a pointer")
}
typ, val := dereferencePointers(reflect.TypeOf(v), reflect.ValueOf(v))
switch {
case isModelType(typ):
if topLevel || bytes.Equal(b, []byte("null")) {
d := json.NewDecoder(bytes.NewReader(b))
if disallowUnknownFields {
d.DisallowUnknownFields()
}
return d.Decode(v)
}
var unmarhsaled map[string]json.RawMessage
if err := json.Unmarshal(b, &unmarhsaled); err != nil {
return err
}
var additionalPropertiesField *reflect.StructField
var additionalPropertiesValue *reflect.Value
for i := 0; i < typ.NumField(); i++ {
field := typ.Field(i)
fieldVal := val.Field(i)
fieldName := field.Name
jsonTag := field.Tag.Get("json")
if jsonTag != "" {
for _, tag := range strings.Split(jsonTag, ",") {
if tag != "omitempty" {
fieldName = tag
}
}
}
if field.Tag.Get("additionalProperties") == "true" {
additionalPropertiesField = &field
additionalPropertiesValue = &fieldVal
continue
}
// If we receive a value for a const field ignore it but mark it as unmarshaled
if field.Tag.Get("const") != "" {
if r, ok := unmarhsaled[fieldName]; ok {
val := string(r)
if strings.HasPrefix(val, `"`) && strings.HasSuffix(val, `"`) {
val = val[1 : len(val)-1]
}
if val != field.Tag.Get("const") {
return fmt.Errorf("const field %s does not match expected value %s", fieldName, field.Tag.Get("const"))
}
delete(unmarhsaled, fieldName)
}
} else if !field.IsExported() {
continue
}
value, ok := unmarhsaled[fieldName]
if !ok {
defaultTag := field.Tag.Get("default")
if defaultTag != "" {
value = handleDefaultConstValue(defaultTag, fieldVal.Interface(), field.Tag)
ok = true
}
} else {
delete(unmarhsaled, fieldName)
}
if ok {
if err := unmarshalValue(value, fieldVal, field.Tag, disallowUnknownFields); err != nil {
return err
}
}
}
keys := make([]string, 0, len(unmarhsaled))
for k := range unmarhsaled {
keys = append(keys, k)
}
if len(keys) > 0 {
if disallowUnknownFields && (additionalPropertiesField == nil || additionalPropertiesValue == nil) {
return fmt.Errorf("unknown fields: %v", keys)
}
if additionalPropertiesField != nil && additionalPropertiesValue != nil {
if additionalPropertiesValue.Kind() != reflect.Map {
return fmt.Errorf("additionalProperties must be a map")
}
additionalPropertiesValue.Set(reflect.MakeMap(additionalPropertiesField.Type))
for key, value := range unmarhsaled {
val := reflect.New(additionalPropertiesField.Type.Elem())
if err := unmarshalValue(value, val, additionalPropertiesField.Tag, disallowUnknownFields); err != nil {
return err
}
additionalPropertiesValue.SetMapIndex(reflect.ValueOf(key), val.Elem())
}
}
}
default:
return unmarshalValue(b, reflect.ValueOf(v), tag, disallowUnknownFields)
}
return nil
}
func marshalValue(v interface{}, tag reflect.StructTag) (json.RawMessage, error) {
constTag := tag.Get("const")
if constTag != "" {
return handleDefaultConstValue(constTag, v, tag), nil
}
if isNil(reflect.TypeOf(v), reflect.ValueOf(v)) {
defaultTag := tag.Get("default")
if defaultTag != "" {
return handleDefaultConstValue(defaultTag, v, tag), nil
}
return []byte("null"), nil
}
typ, val := dereferencePointers(reflect.TypeOf(v), reflect.ValueOf(v))
switch typ.Kind() {
case reflect.Map:
if isNil(typ, val) {
return []byte("null"), nil
}
out := map[string]json.RawMessage{}
for _, key := range val.MapKeys() {
itemVal := val.MapIndex(key)
if isNil(itemVal.Type(), itemVal) {
out[key.String()] = []byte("null")
continue
}
r, err := marshalValue(itemVal.Interface(), tag)
if err != nil {
return nil, err
}
out[key.String()] = r
}
return json.Marshal(out)
case reflect.Slice, reflect.Array:
if isNil(typ, val) {
return []byte("null"), nil
}
out := []json.RawMessage{}
for i := 0; i < val.Len(); i++ {
itemVal := val.Index(i)
if isNil(itemVal.Type(), itemVal) {
out = append(out, []byte("null"))
continue
}
r, err := marshalValue(itemVal.Interface(), tag)
if err != nil {
return nil, err
}
out = append(out, r)
}
return json.Marshal(out)
case reflect.Struct:
switch typ {
case reflect.TypeOf(time.Time{}):
return []byte(fmt.Sprintf(`"%s"`, val.Interface().(time.Time).Format(time.RFC3339Nano))), nil
case reflect.TypeOf(big.Int{}):
format := tag.Get("bigint")
if format == "string" {
b := val.Interface().(big.Int)
return []byte(fmt.Sprintf(`"%s"`, (&b).String())), nil
}
case reflect.TypeOf(decimal.Big{}):
format := tag.Get("decimal")
if format == "number" {
b := val.Interface().(decimal.Big)
f, ok := (&b).Float64()
if ok {
return []byte(b.String()), nil
}
return []byte(fmt.Sprintf(`%f`, f)), nil
}
}
}
return json.Marshal(v)
}
func handleDefaultConstValue(tagValue string, val interface{}, tag reflect.StructTag) json.RawMessage {
if tagValue == "null" {
return []byte("null")
}
typ := dereferenceTypePointer(reflect.TypeOf(val))
switch typ {
case reflect.TypeOf(time.Time{}):
return []byte(fmt.Sprintf(`"%s"`, tagValue))
case reflect.TypeOf(big.Int{}):
bigIntTag := tag.Get("bigint")
if bigIntTag == "string" {
return []byte(fmt.Sprintf(`"%s"`, tagValue))
}
case reflect.TypeOf(decimal.Big{}):
decimalTag := tag.Get("decimal")
if decimalTag != "number" {
return []byte(fmt.Sprintf(`"%s"`, tagValue))
}
case reflect.TypeOf(types.Date{}):
return []byte(fmt.Sprintf(`"%s"`, tagValue))
default:
if typ.Kind() == reflect.String {
return []byte(fmt.Sprintf(`"%s"`, tagValue))
}
}
return []byte(tagValue)
}
func unmarshalValue(value json.RawMessage, v reflect.Value, tag reflect.StructTag, disallowUnknownFields bool) error {
if bytes.Equal(value, []byte("null")) {
if v.CanAddr() {
return json.Unmarshal(value, v.Addr().Interface())
} else {
return json.Unmarshal(value, v.Interface())
}
}
typ := dereferenceTypePointer(v.Type())
switch typ.Kind() {
case reflect.Map:
if bytes.Equal(value, []byte("null")) || !isComplexValueType(dereferenceTypePointer(typ.Elem())) {
if v.CanAddr() {
return json.Unmarshal(value, v.Addr().Interface())
} else {
return json.Unmarshal(value, v.Interface())
}
}
var unmarhsaled map[string]json.RawMessage
if err := json.Unmarshal(value, &unmarhsaled); err != nil {
return err
}
m := reflect.MakeMap(typ)
for k, value := range unmarhsaled {
itemVal := reflect.New(typ.Elem())
if err := unmarshalValue(value, itemVal, tag, disallowUnknownFields); err != nil {
return err
}
m.SetMapIndex(reflect.ValueOf(k), itemVal.Elem())
}
v.Set(m)
return nil
case reflect.Slice, reflect.Array:
if bytes.Equal(value, []byte("null")) || !isComplexValueType(dereferenceTypePointer(typ.Elem())) {
if v.CanAddr() {
return json.Unmarshal(value, v.Addr().Interface())
} else {
return json.Unmarshal(value, v.Interface())
}
}
var unmarhsaled []json.RawMessage
if err := json.Unmarshal(value, &unmarhsaled); err != nil {
return err
}
arrVal := v
for _, value := range unmarhsaled {
itemVal := reflect.New(typ.Elem())
if err := unmarshalValue(value, itemVal, tag, disallowUnknownFields); err != nil {
return err
}
arrVal = reflect.Append(arrVal, itemVal.Elem())
}
v.Set(arrVal)
return nil
case reflect.Struct:
switch typ {
case reflect.TypeOf(time.Time{}):
var s string
if err := json.Unmarshal(value, &s); err != nil {
return err
}
t, err := time.Parse(time.RFC3339Nano, s)
if err != nil {
return fmt.Errorf("failed to parse string as time.Time: %w", err)
}
if v.Kind() == reflect.Ptr {
if v.IsNil() {
v.Set(reflect.New(typ))
}
v = v.Elem()
}
v.Set(reflect.ValueOf(t))
return nil
case reflect.TypeOf(big.Int{}):
var b *big.Int
format := tag.Get("bigint")
if format == "string" {
var s string
if err := json.Unmarshal(value, &s); err != nil {
return err
}
var ok bool
b, ok = new(big.Int).SetString(s, 10)
if !ok {
return fmt.Errorf("failed to parse string as big.Int")
}
} else {
if err := json.Unmarshal(value, &b); err != nil {
return err
}
}
if v.Kind() == reflect.Ptr && v.Elem().Kind() == reflect.Ptr {
v = v.Elem()
}
v.Set(reflect.ValueOf(b))
return nil
case reflect.TypeOf(decimal.Big{}):
var d *decimal.Big
format := tag.Get("decimal")
if format == "number" {
var ok bool
d, ok = new(decimal.Big).SetString(string(value))
if !ok {
return fmt.Errorf("failed to parse number as decimal.Big")
}
} else {
if err := json.Unmarshal(value, &d); err != nil {
return err
}
}
if v.Kind() == reflect.Ptr && v.Elem().Kind() == reflect.Ptr {
v = v.Elem()
}
v.Set(reflect.ValueOf(d))
return nil
case reflect.TypeOf(types.Date{}):
var s string
if err := json.Unmarshal(value, &s); err != nil {
return err
}
d, err := types.DateFromString(s)
if err != nil {
return fmt.Errorf("failed to parse string as types.Date: %w", err)
}
if v.Kind() == reflect.Ptr {
if v.IsNil() {
v.Set(reflect.New(typ))
}
v = v.Elem()
}
v.Set(reflect.ValueOf(d))
return nil
}
}
var val interface{}
if v.CanAddr() {
val = v.Addr().Interface()
} else {
val = v.Interface()
}
d := json.NewDecoder(bytes.NewReader(value))
if disallowUnknownFields {
d.DisallowUnknownFields()
}
return d.Decode(val)
}
func dereferencePointers(typ reflect.Type, val reflect.Value) (reflect.Type, reflect.Value) {
if typ.Kind() == reflect.Ptr {
typ = typ.Elem()
val = val.Elem()
} else {
return typ, val
}
return dereferencePointers(typ, val)
}
func dereferenceTypePointer(typ reflect.Type) reflect.Type {
if typ.Kind() == reflect.Ptr {
typ = typ.Elem()
} else {
return typ
}
return dereferenceTypePointer(typ)
}
func isComplexValueType(typ reflect.Type) bool {
switch typ.Kind() {
case reflect.Struct:
switch typ {
case reflect.TypeOf(time.Time{}):
fallthrough
case reflect.TypeOf(big.Int{}):
fallthrough
case reflect.TypeOf(decimal.Big{}):
fallthrough
case reflect.TypeOf(types.Date{}):
return true
}
}
return false
}
func isModelType(typ reflect.Type) bool {
if isComplexValueType(typ) {
return false
}
if typ.Kind() == reflect.Struct {
return true
}
return false
}