github.com/6543-forks/go-swagger@v0.26.0/generator/templates/serializers/tupleserializer.gotmpl (about) 1 {{ define "tupleSerializer" }} 2 // UnmarshalJSON unmarshals this tuple type from a JSON array 3 func ({{.ReceiverName}} *{{ pascalize .Name }}) UnmarshalJSON(raw []byte) error { 4 // stage 1, get the array but just the array 5 var stage1 []json.RawMessage 6 buf := bytes.NewBuffer(raw) 7 dec := json.NewDecoder(buf) 8 dec.UseNumber() 9 10 if err := dec.Decode(&stage1); err != nil { 11 return err 12 } 13 14 // stage 2: hydrates struct members with tuple elements 15 {{- if .AdditionalItems }} 16 var lastIndex int 17 {{ end }} 18 {{ range $idx, $val := .Properties }}if len(stage1) > {{ $idx }} { 19 var data{{ pascalize .Name }} {{ template "dereffedSchemaType" . }} 20 buf = bytes.NewBuffer(stage1[{{ $idx }}]) 21 dec := json.NewDecoder(buf) 22 dec.UseNumber() 23 if err := dec.Decode(&data{{ pascalize .Name }}); err != nil { 24 return err 25 } 26 {{ .ReceiverName }}.{{ if .IsExported }}{{ pascalize .Name }}{{ else }}{{ camelize .Name }}{{ end }} = {{ if .IsNullable }}&{{ end }}data{{ pascalize .Name }} 27 {{ if $.AdditionalItems }} 28 lastIndex = {{ $idx }} 29 {{ end }} 30 } 31 {{ end }} 32 {{ if .AdditionalItems }} 33 // stage 3: hydrates AdditionalItems 34 if len(stage1) > lastIndex+1 { 35 for _, val := range stage1[lastIndex+1:] { 36 var toadd {{ template "schemaType" .AdditionalItems }} 37 buf = bytes.NewBuffer(val) 38 dec := json.NewDecoder(buf) 39 dec.UseNumber() 40 if err := dec.Decode({{ if not .AdditionalItems.IsNullable }}&{{ end }}toadd); err != nil { 41 return err 42 } 43 {{- with .AdditionalItems }} 44 {{ $.ValueExpression }}.{{- if .IsExported }}{{ pascalize .Name }}{{ else }}{{ camelize .Name }}{{ end }} = append({{ $.ValueExpression }}.{{- if .IsExported }}{{ pascalize .Name }}{{ else }}{{ camelize .Name }}{{ end }}, toadd) 45 {{- end }} 46 } 47 } 48 {{- end }} 49 return nil 50 } 51 52 // MarshalJSON marshals this tuple type into a JSON array 53 func ({{.ReceiverName}} {{ pascalize .Name }}) MarshalJSON() ([]byte, error) { 54 data := []interface{}{ 55 {{ range .Properties -}} 56 {{.ReceiverName}}.{{ pascalize .Name }}, 57 {{- end }} 58 } 59 {{ with .AdditionalItems }} 60 for _, v := range {{ $.ValueExpression }}.{{ if .IsExported }}{{ pascalize .Name }}{{ else }}{{ camelize .Name }}{{ end }} { 61 data = append(data, v) 62 } 63 {{- end }} 64 return json.Marshal(data) 65 } 66 {{- end }}