-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathunmarshal.go
48 lines (45 loc) · 958 Bytes
/
unmarshal.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
package soq
import (
"encoding/json"
"fmt"
)
func unmarshalQuestion(raw json.RawMessage) (Question, error) {
typ := struct {
Type string `json:"type"`
}{}
if err := json.Unmarshal(raw, &typ); err != nil {
return nil, err
}
switch typ.Type {
case "likert":
l := LikertQuestion{}
if err := json.Unmarshal(raw, &l); err != nil {
return nil, err
}
return &l, nil
default:
return nil, fmt.Errorf("unknown question type %s", typ.Type)
}
}
func (q *Questionnaire) UnmarshalJSON(data []byte) error {
type Alias Questionnaire
aux := &struct {
Questions []json.RawMessage `json:"questions"`
*Alias
}{
Alias: (*Alias)(q),
}
if err := json.Unmarshal(data, &aux); err != nil {
return err
}
outQuestions := make([]*Question, len(aux.Questions))
for idx, rawQ := range aux.Questions {
q, err := unmarshalQuestion(rawQ)
if err != nil {
return err
}
outQuestions[idx] = &q
}
q.Questions = outQuestions
return nil
}