forked from orus-io/json-schema-generate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
output_tmpl.go
823 lines (721 loc) · 20.2 KB
/
output_tmpl.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
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
package generate
import (
"strings"
"text/template"
)
var streamMarshallerTypes = []string{
"EmptyBool",
"EmptyNumber",
"EmptyString",
"OneOfStringNull",
}
var iteratorUnmashallerTypes = []string{
"EmptyBool",
"EmptyNumber",
"EmptyString",
"OneOfStringNull",
}
var funcs = template.FuncMap{
// comment outputs a string the '// ' in front of each line
"comment": func(s ...string) string {
lines := strings.Split(strings.Join(s, " "), "\n")
return strings.Join(lines, "\n// ")
},
// fieldName creates a field name from a data type
"fieldName": func(s string) string {
if strings.HasPrefix(s, "*") {
s = s[1:]
}
return strings.ToLower(s[0:1]) + s[1:]
},
// capitalize returns the string with the first letter uppered
"capitalize": func(s string) string {
return strings.ToUpper(s[0:1]) + s[1:]
},
// DeferedType removes a leading '*' from a data type
"deferedType": func(s string) string {
if strings.HasPrefix(s, "*") {
s = s[1:]
}
return s
},
// isplainjsontype returns true if the given json type is a pod
"isplainjsontype": func(t string) bool {
switch t {
case "bool":
return true
case "string":
return true
case "number":
return true
case "integer":
return true
case "null":
return true
}
return false
},
// oneOfContainsJsonType returns true if the given oneOf contains the passed jsontype
"oneOfContainsJsonType": func(o OneOf, t string) bool {
for _, ot := range o.Types {
if ot.JSONType == t {
return true
}
}
return false
},
// ispointer returns true if the given type starts with "*"
"ispointer": func(t string) bool {
return t[0] == '*'
},
// isStreamMarshaller returns true if the given type is known to have a MarshalJSONStream function
"isStreamMarshaller": func(t string) bool {
for _, s := range streamMarshallerTypes {
if s == t {
return true
}
}
return false
},
// isIteratorUnmarshaller returns true if the given type is known to have a UnmarshalJSONIterator function
"isIteratorUnmarshaller": func(t string) bool {
for _, s := range iteratorUnmashallerTypes {
if s == t {
return true
}
}
return false
},
}
var headerTmpl = template.Must(template.New("schema-generate").Funcs(funcs).Parse(
`// Code generated by schema-generate. DO NOT EDIT.
package {{.PackageName}}
import (
{{- range $path, $importName := .ImportPaths }}
{{ $importName }}"{{ $path }}"
{{- end }}
)
`))
var mainTmpl = template.Must(template.New("schema-generate").Funcs(funcs).Parse(
`{{- with $top := . -}}
func ValueTypeToString(valueType jsoniter.ValueType) string {
switch valueType {
case jsoniter.StringValue:
return "string"
case jsoniter.NumberValue:
return "number"
case jsoniter.NilValue:
return "nil"
case jsoniter.BoolValue:
return "bool"
case jsoniter.ArrayValue:
return "array"
case jsoniter.ObjectValue:
return "object"
default:
return "invalid"
}
}
type commaTracker struct {
stream *jsoniter.Stream
started bool
}
func (t *commaTracker) More() {
if t.started {
t.stream.WriteMore()
} else {
t.started = true
}
}
type isEmptyChecker interface {
IsEmpty() bool
}
// IsEmpty reports whether v is zero struct
// Does not support cycle pointers for performance, so as json
func IsEmpty(v interface{}) bool {
if i, ok := v.(isEmptyChecker); ok {
return i.IsEmpty()
}
rv := {{ .Pkg "reflect" }}.ValueOf(v)
return !rv.IsValid() || rv.IsZero()
}
var (
jsonNullValue = []byte("null")
)
{{- range $t, $tname := .EmptyTypes }}
// New{{ $tname }} creates a non-empty {{ $tname }}
func New{{ $tname }}(value {{ $t }}) {{ $tname }} {
return {{ $tname }}{value, true}
}
// {{ $tname }} is {{ $t }} or nothing
type {{ $tname }} struct {
{{ capitalize $t }} {{ $t }}
Valid bool // Valid is true if {{ capitalize $t }} is not empty
}
func (t {{ $tname }}) IsEmpty() bool {
return !t.Valid
}
func (t {{ $tname }}) MarshalJSON() ([]byte, error) {
if t.Valid {
return jsoniter.Marshal(t.{{ capitalize $t }})
}
return []byte("\"\""), nil
}
func (t *{{ $tname }}) Set(value {{ $t }}) {
t.{{ capitalize $t }} = value
t.Valid = true
}
func (t *{{ $tname }}) Unset() {
{{- if eq $t "string" }}
t.String = ""
{{- else if eq $t "bool" }}
t.Bool = false
{{- else if eq $t "int" }}
t.Int = 0
{{- else if eq $t "float64" }}
t.Float64 = 0.0
{{- end}}
t.Valid = false
}
func (t {{ $tname }}) MarshalJSONStream(stream *jsoniter.Stream) {
if t.Valid {
stream.Write{{ capitalize $t }}(t.{{ capitalize $t }})
} else {
{{- if eq $t "string" }}
stream.WriteString("")
{{- else if eq $t "bool" }}
stream.WriteBool(false)
{{- else if eq $t "int" }}
stream.WriteInt(0)
{{- else if eq $t "float64" }}
stream.WriteFloat64(0.0)
{{- end}}
}
}
func (t *{{ $tname }}) UnmarshalJSONIterator(iter *jsoniter.Iterator) {
t.{{ capitalize $t }} = iter.Read{{ capitalize $t }}()
t.Valid = iter.Error == nil
}
func (t *{{ $tname }}) UnmarshalJSON(data []byte) error {
if err := jsoniter.Unmarshal(data, &t.{{ capitalize $t }}); err != nil {
return err
}
t.Valid = true
return nil
}
{{- end }}
// OneOfStringNull is a 'string' or a 'null', and can be emptied
type OneOfStringNull struct {
currentType jsoniter.ValueType
stringValue string
}
// NewOneOfStringNull creates a empty OneOfStringNull
func NewOneOfStringNull() OneOfStringNull {
return OneOfStringNull{jsoniter.InvalidValue, ""}
}
// NewOneOfStringNullString creates a OneOfStringNull of type string
func NewOneOfStringNullString(value string) OneOfStringNull {
return OneOfStringNull{jsoniter.StringValue, value}
}
// NewOneOfStringNullNull creates a OneOfStringNull of type null
func NewOneOfStringNullNull() OneOfStringNull {
return OneOfStringNull{jsoniter.NilValue, ""}
}
// IsEmpty returns true if the value is empty
func (value *OneOfStringNull) IsEmpty() bool {
return value.currentType == jsoniter.InvalidValue
}
// IsNull returns true if the value is 'null'
func (value *OneOfStringNull) IsNull() bool {
return value.currentType == jsoniter.NilValue
}
// IsString returns true if the value is a string
func (value *OneOfStringNull) IsString() bool {
return value.currentType == jsoniter.StringValue
}
// StringValue returns the current value if IsString() is true, "" otherwise
func (value *OneOfStringNull) StringValue() string {
if value.currentType == jsoniter.StringValue {
return value.stringValue
}
return ""
}
// NullString returns the current value as a sql.NullString
func (value *OneOfStringNull) NullString() {{ .Pkg "database/sql" }}.NullString {
return sql.NullString{
Valid: value.currentType == jsoniter.StringValue,
String: value.stringValue,
}
}
// MarshalJSONStream serializes to a jsoniter Stream
func (value OneOfStringNull) MarshalJSONStream(stream *{{ .Pkg "jsoniter" "github.com/json-iterator/go" }}.Stream) {
if value.currentType == jsoniter.StringValue {
stream.WriteString(value.stringValue)
} else {
stream.WriteNil()
}
}
// MarshalJSON serialize to json
func (value OneOfStringNull) MarshalJSON() ([]byte, error) {
switch value.currentType {
case jsoniter.InvalidValue:
return jsonNullValue, nil
case jsoniter.NilValue:
return jsonNullValue, nil
case jsoniter.StringValue:
return jsoniter.Marshal(value.stringValue)
}
return nil, {{ $top.Pkg "fmt" }}.Errorf(
"OneOfStringNull unsupported type: %s",
ValueTypeToString(value.currentType))
}
func (value *OneOfStringNull) UnmarshalJSONIterator(iter *jsoniter.Iterator) {
switch t := iter.WhatIsNext(); t {
case jsoniter.NilValue:
iter.ReadNil()
value.currentType = jsoniter.NilValue
case jsoniter.StringValue:
value.currentType = jsoniter.StringValue
value.stringValue = iter.ReadString()
default:
iter.ReportError("Read", fmt.Sprintf("unexpected value type: %v", t))
}
}
// UnmarshalJSON unserialize a OneOfStringNull from json
func (value *OneOfStringNull) UnmarshalJSON(data []byte) error {
if {{ .Pkg "bytes" }}.Equal(data, jsonNullValue) {
value.currentType = jsoniter.NilValue
} else {
if err := jsoniter.Unmarshal(data, &value.stringValue); err != nil {
return err
}
value.currentType = jsoniter.StringValue
}
return nil
}
// OneOfNumberNull is a 'string' or a 'null', and can be emptied
type OneOfNumberNull struct {
currentType jsoniter.ValueType
numberValue float64
}
// NewOneOfNumberNull creates a empty OneOfNumberNull
func NewOneOfNumberNull() OneOfNumberNull {
return OneOfNumberNull{jsoniter.InvalidValue, 0}
}
// NewOneOfNumberNullNumber creates a OneOfNumberNull of type number
func NewOneOfNumberNullNumber(value float64) OneOfNumberNull {
return OneOfNumberNull{jsoniter.NumberValue, value}
}
// NewOneOfNumberNullNull creates a OneOfNumberNull of type null
func NewOneOfNumberNullNull() OneOfNumberNull {
return OneOfNumberNull{jsoniter.NilValue, 0}
}
// IsEmpty returns true if the value is empty
func (value *OneOfNumberNull) IsEmpty() bool {
return value.currentType == jsoniter.InvalidValue
}
// IsNull returns true if the value is 'null'
func (value *OneOfNumberNull) IsNull() bool {
return value.currentType == jsoniter.NilValue
}
// IsNumber returns true if the value is a number
func (value *OneOfNumberNull) IsNumber() bool {
return value.currentType == jsoniter.NumberValue
}
// NumberValue returns the current value if IsNumber() is true, 0 otherwise
func (value *OneOfNumberNull) NumberValue() float64 {
if value.currentType == jsoniter.NumberValue {
return value.numberValue
}
return 0
}
// MarshalJSON serialize to json
func (value OneOfNumberNull) MarshalJSON() ([]byte, error) {
switch value.currentType {
case jsoniter.InvalidValue:
return jsonNullValue, nil
case jsoniter.NilValue:
return jsonNullValue, nil
case jsoniter.NumberValue:
return jsoniter.Marshal(value.numberValue)
}
return nil, fmt.Errorf(
"OneOfNumberNull unsupported type: %s",
ValueTypeToString(value.currentType))
}
// UnmarshalJSON unserialize a OneOfNumberNull from json
func (value *OneOfNumberNull) UnmarshalJSON(data []byte) error {
if bytes.Equal(data, jsonNullValue) {
value.currentType = jsoniter.NilValue
} else {
if err := jsoniter.Unmarshal(data, &value.numberValue); err != nil {
return err
}
value.currentType = jsoniter.NumberValue
}
return nil
}
// OneOfBoolNull is a 'bool' or a 'null', and can be emptied
type OneOfBoolNull struct {
currentType jsoniter.ValueType
boolValue bool
}
// NewOneOfBoolNull creates a empty OneOfBoolNull
func NewOneOfBoolNull() OneOfBoolNull {
return OneOfBoolNull{jsoniter.InvalidValue, false}
}
// NewOneOfBoolNullBool creates a OneOfBoolNull of type number
func NewOneOfBoolNullBool(value bool) OneOfBoolNull {
return OneOfBoolNull{jsoniter.BoolValue, value}
}
// NewOneOfBoolNullNull creates a OneOfBoolNull of type null
func NewOneOfBoolNullNull() OneOfBoolNull {
return OneOfBoolNull{jsoniter.NilValue, false}
}
// IsEmpty returns true if the value is empty
func (value *OneOfBoolNull) IsEmpty() bool {
return value.currentType == jsoniter.InvalidValue
}
// IsNull returns true if the value is 'null'
func (value *OneOfBoolNull) IsNull() bool {
return value.currentType == jsoniter.NilValue
}
// IsBool returns true if the value is a bool
func (value *OneOfBoolNull) IsBool() bool {
return value.currentType == jsoniter.BoolValue
}
// BoolValue returns the current value if IsBool() is true, false otherwise
func (value *OneOfBoolNull) BoolValue() bool {
if value.currentType == jsoniter.BoolValue {
return value.boolValue
}
return false
}
// MarshalJSON serialize to json
func (value OneOfBoolNull) MarshalJSON() ([]byte, error) {
switch value.currentType {
case jsoniter.InvalidValue:
return jsonNullValue, nil
case jsoniter.NilValue:
return jsonNullValue, nil
case jsoniter.BoolValue:
return jsoniter.Marshal(value.boolValue)
}
return nil, fmt.Errorf(
"OneOfBoolNull unsupported type: %s",
ValueTypeToString(value.currentType))
}
// UnmarshalJSON unserialize a OneOfBoolNull from json
func (value *OneOfBoolNull) UnmarshalJSON(data []byte) error {
if bytes.Equal(data, jsonNullValue) {
value.currentType = jsoniter.NilValue
} else {
if err := jsoniter.Unmarshal(data, &value.boolValue); err != nil {
return err
}
value.currentType = jsoniter.BoolValue
}
return nil
}
{{- range $oneOf := .OneOfs }}
type {{ .Name }}Enum = int
const (
{{ $oneOf.Name }}EnumNotSet {{ $oneOf.Name }}Enum = iota
{{- range $i, $type := .Types }}
{{ $oneOf.Name }}Enum{{ .ShortType }}
{{- end }}
)
type {{ .Name }} struct {
Type {{ $oneOf.Name }}Enum
value interface{}
}
func (o {{ $oneOf.Name }}) IsNotSet() bool {
return o.Type == {{ $oneOf.Name }}EnumNotSet
}
{{- range .Types }}
func (o {{ $oneOf.Name }}) Is{{ .ShortType }}() bool {
return o.Type == {{ $oneOf.Name }}Enum{{ .ShortType }}
}
{{- if ne "nil" .Type}}
func (o {{ $oneOf.Name }}) {{ .ShortType }}() {{ .Type }} {
return o.value.({{ .Type }})
}
{{- end }}
func (o *{{ $oneOf.Name }}) Set{{ .ShortType }}(
{{- if ne "nil" .Type}}v {{ .Type }}{{ end -}}
) {
{{- if ne "nil" .Type }}
o.value = v
{{- end }}
o.Type = {{ $oneOf.Name }}Enum{{ .ShortType }}
}
{{- end }}
func (o {{ $oneOf.Name }}) MarshalJSON() ([]byte, error) {
buf := bytes.NewBuffer(nil)
stream := jsoniter.ConfigDefault.BorrowStream(buf)
o.MarshalJSONStream(stream)
err := stream.Error
jsoniter.ConfigDefault.ReturnStream(stream)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func (o {{ $oneOf.Name }}) MarshalJSONStream(stream *jsoniter.Stream) {
switch o.Type {
{{- range .Types }}
case {{ $oneOf.Name }}Enum{{ .ShortType }}:
{{- if eq "bool" .Type }}
stream.WriteBool(o.value.(bool))
{{- else if eq "string" .Type }}
stream.WriteString(o.value.(string))
{{- else if eq "int" .Type }}
stream.WriteInt(o.value.(int))
{{- else if eq "float64" .Type }}
stream.WriteFloat64(o.value.(float64))
{{- else if eq "nil" .Type }}
stream.WriteNil()
{{- else }}
stream.WriteVal(o.value)
{{- end }}
{{- end }}
}
}
func (o *{{ $oneOf.Name }}) UnmarshalJSON(data []byte) error {
iter := jsoniter.ConfigDefault.BorrowIterator(data)
o.UnmarshalJSONIterator(iter)
err := iter.Error
jsoniter.ConfigDefault.ReturnIterator(iter)
return err
}
func (o *{{ $oneOf.Name }}) UnmarshalJSONIterator(iter *jsoniter.Iterator) {
switch t := iter.WhatIsNext(); t {
{{- range .Types }}
{{- if eq "nil" .Type }}
case jsoniter.NilValue:
iter.ReadNil()
o.SetNil()
{{- else if eq "bool" .Type }}
case jsoniter.BoolValue:
o.SetBool(iter.ReadBool())
{{- else if eq "string" .Type }}
case jsoniter.StringValue:
o.SetString(iter.ReadString())
{{- end }}
{{- end }}
{{- if and (oneOfContainsJsonType . "integer") (oneOfContainsJsonType . "number") }}
case jsoniter.NumberValue:
b := iter.SkipAndReturnBytes()
if iter.Error == io.EOF {
iter.Error = nil
}
subiter := jsoniter.ConfigDefault.BorrowIterator(b)
defer jsoniter.ConfigDefault.ReturnIterator(subiter)
i := subiter.ReadInt()
if subiter.Error == nil || subiter.Error == {{ $top.Pkg "io" }}.EOF {
o.SetInt(i)
return
}
subiter.Error = nil
subiter.ResetBytes(b)
f := subiter.ReadFloat64()
if subiter.Error == nil || subiter.Error == io.EOF {
o.SetFloat64(f)
return
}
iter.Error = subiter.Error
{{- else if oneOfContainsJsonType . "integer" }}
case jsoniter.NumberValue:
o.SetInt(iter.ReadFloat64())
{{- else if oneOfContainsJsonType . "number" }}
case jsoniter.NumberValue:
o.SetFloat64(iter.ReadFloat64())
{{- end }}
{{- if oneOfContainsJsonType . "" }}
case jsoniter.ObjectValue:
// I would have used ReadAny, but its 'ToVal' function does not returns
// the underlying iterator errors, hence makes it impossible to implement
// a proper oneOf
buf := iter.SkipAndReturnBytes()
var lastError error
{{- range .Types }}
{{- if eq "" .JSONType }}
{ // attempt to read a {{ .Type }}
subIter := jsoniter.ConfigDefault.BorrowIterator(buf)
var value {{ deferedType .Type }}
subIter.ReadVal(&value)
lastError = subIter.Error
jsoniter.ConfigDefault.ReturnIterator(subIter)
if lastError == nil {
o.Set{{ .ShortType }}({{ if ispointer .Type }}&{{ end }}value)
return
}
}
{{- end }}
{{- end }}
iter.Error = lastError
{{- end }}
}
}
{{- end }}
{{- range .Aliases }}
// {{ .Name }} ...
type {{ .Name }} {{ .Type }}
{{- end -}}
{{- range .Structs }}
// {{ comment .Name .Description }}
type {{ .Name }} struct {
{{- range .Fields }}
// {{ comment .Name .Description }}
{{ .Name }} {{ .Type }} {{ $top.Backquote }}json:"{{ .JSONName }}{{ if not .Required }},omitempty{{ end }}"{{ $top.Backquote }}
{{ end }}
}
{{- end -}}
{{- range $struct := .Structs }}
{{ if .GenerateCode }}
// MarshalJSON serializes to JSON
func (s *{{ .Name }}) MarshalJSON() ([]byte, error) {
buf := bytes.NewBuffer(nil)
stream := jsoniter.ConfigDefault.BorrowStream(buf)
s.MarshalJSONStream(stream)
stream.Flush()
err := stream.Error
jsoniter.ConfigDefault.ReturnStream(stream)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func (s {{ .Name }}) MarshalJSONStream(stream *jsoniter.Stream) {
{{- if .NoProp }}
stream.WriteEmptyObject()
{{- else }}
stream.WriteObjectStart()
ct := commaTracker{stream:stream}
{{- range .Fields }}
{{- if ne .JSONName "-" }}
// Marshal the {{ .Name }} field
{{- if and .Required .IsPointer }}
// {{ .Name }} is required
if s.{{ .Name }} == nil {
stream.Error = {{ $top.Pkg "errors" }}.New("{{ .Name }} ({{ .JSONName }}) is a required")
return
}
{{- end }}
{{- if not .Required }}
if !IsEmpty(s.{{ .Name }}) {
{{- end }}
ct.More()
stream.WriteObjectField("{{ .JSONName }}")
{{- if eq .Type "string" }}
stream.WriteString(s.{{ .Name }})
{{- else if isStreamMarshaller .Type }}
s.{{ .Name }}.MarshalJSONStream(stream)
{{- else }}
stream.WriteVal(s.{{ .Name }})
if stream.Error != nil {
return
}
{{- end }}
{{- if not .Required }}
}
{{- end}}
{{- end}}
{{- end}}
{{- if and .AdditionalType (ne .AdditionalType "false")}}
for key, value := range s.AdditionalProperties {
ct.More()
stream.WriteObjectField(key)
stream.WriteVal(value)
}
{{- end}}
stream.WriteObjectEnd()
{{- end}}
}
func (s *{{ .Name }}) UnmarshalJSON(data []byte) error {
iter := jsoniter.ConfigDefault.BorrowIterator(data)
s.UnmarshalJSONIterator(iter)
err := iter.Error
jsoniter.ConfigDefault.ReturnIterator(iter)
return err
}
func (s *{{ .Name }}) UnmarshalJSONIterator(iter *jsoniter.Iterator) {
{{- range .Fields }}
{{- if .Required}}
{{ .Name }}Received := false
{{- end}}
{{- end}}
for field := iter.ReadObject(); field != ""; field = iter.ReadObject() {
switch field {
{{- range .Fields }}
{{- if ne .JSONName "-" }}
case "{{ .JSONName }}":
{{- if and $top.AlwaysAcceptFalse (ne .Type "bool") (ne .Type "OneOfBoolNull")}}
if iter.WhatIsNext() == jsoniter.BoolValue {
if iter.ReadBool() {
iter.ReportError("reading field {{ .JSONName }}", "{{ .JSONName }} is 'true', but the expected type is {{ .Type }}")
return
}
// received 'false', which we accept and ignore for now
}
{{- end}}
{{- if eq .Type "string" }}
s.{{ .Name }} = iter.ReadString()
{{- if .Enum }}
{{- if eq 1 (len .Enum) }}
if s.{{ .Name }} != {{ index .Enum 0 }} {
iter.ReportError(
"{{ .JSONName }}",
fmt.Sprintf("Expected %s, got \"%s\"", {{ index .Enum 0 }}, s.{{ .Name }}),
)
}
{{- else}}
{{- end }}
{{- end }}
{{- else if eq .Type "bool" }}
s.{{ .Name }} = iter.ReadBool()
{{- else if isIteratorUnmarshaller .Type }}
s.{{ .Name }}.UnmarshalJSONIterator(iter)
{{- else }}
iter.ReadVal(&s.{{ .Name }})
{{- end}}
if iter.Error != nil {
return
}
{{- if .Required}}
{{ .Name }}Received = true
{{- end}}
{{- end}}
{{- end}}
default:
{{- if eq .AdditionalType "false" }}
iter.ReportError("reading {{ .Name }}", "additional property not allowed: \"" + field + "\"")
return
{{- else if .AdditionalType }}
if s.AdditionalProperties == nil {
s.AdditionalProperties = make(map[string]{{ .AdditionalType }}, 0)
}
var additionalValue {{ .AdditionalType }}
iter.ReadVal(&additionalValue)
if iter.Error != nil {
return
}
s.AdditionalProperties[field]= additionalValue
{{- else }}
// Ignore the additional property
iter.Skip()
{{- end }}
}
}
{{- range .Fields }}
{{- if .Required}}
if !{{ .Name }}Received {
iter.ReportError("validating {{ $struct.Name }}", "\"{{ .JSONName }}\" is required but was not present")
}
{{- end}}
{{- end}}
}
{{- end -}}
{{- end -}}
{{- end -}}
`))