From 2d3ec00166cfb9d6ba804b3118ce4525308a7df2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Armin=20Pa=C5=A1ali=C4=87?= Date: Thu, 18 Jan 2018 23:53:24 +0100 Subject: [PATCH] Address the issue when the enum value is passed as null --- example/shirtsize_jsonenums.go | 5 +++++ example/weekday_jsonenums.go | 5 +++++ template.go | 3 +++ 3 files changed, 13 insertions(+) diff --git a/example/shirtsize_jsonenums.go b/example/shirtsize_jsonenums.go index af60b7e..22ac5df 100644 --- a/example/shirtsize_jsonenums.go +++ b/example/shirtsize_jsonenums.go @@ -41,6 +41,7 @@ func init() { } } +// MarshalJSON is generated so ShirtSize satisfies json.Marshaler. func (r ShirtSize) MarshalJSON() ([]byte, error) { if s, ok := interface{}(r).(fmt.Stringer); ok { return json.Marshal(s.String()) @@ -52,7 +53,11 @@ func (r ShirtSize) MarshalJSON() ([]byte, error) { return json.Marshal(s) } +// UnmarshalJSON is generated so ShirtSize satisfies json.Unmarshaler. func (r *ShirtSize) UnmarshalJSON(data []byte) error { + if string(data) == "null" { + return nil + } var s string if err := json.Unmarshal(data, &s); err != nil { return fmt.Errorf("ShirtSize should be a string, got %s", data) diff --git a/example/weekday_jsonenums.go b/example/weekday_jsonenums.go index c24d250..8483451 100644 --- a/example/weekday_jsonenums.go +++ b/example/weekday_jsonenums.go @@ -44,6 +44,7 @@ func init() { } } +// MarshalJSON is generated so WeekDay satisfies json.Marshaler. func (r WeekDay) MarshalJSON() ([]byte, error) { if s, ok := interface{}(r).(fmt.Stringer); ok { return json.Marshal(s.String()) @@ -55,7 +56,11 @@ func (r WeekDay) MarshalJSON() ([]byte, error) { return json.Marshal(s) } +// UnmarshalJSON is generated so WeekDay satisfies json.Unmarshaler. func (r *WeekDay) UnmarshalJSON(data []byte) error { + if string(data) == "null" { + return nil + } var s string if err := json.Unmarshal(data, &s); err != nil { return fmt.Errorf("WeekDay should be a string, got %s", data) diff --git a/template.go b/template.go index 332c2a3..562cd8d 100644 --- a/template.go +++ b/template.go @@ -65,6 +65,9 @@ func (r {{$typename}}) MarshalJSON() ([]byte, error) { // UnmarshalJSON is generated so {{$typename}} satisfies json.Unmarshaler. func (r *{{$typename}}) UnmarshalJSON(data []byte) error { + if string(data) == "null" { + return nil + } var s string if err := json.Unmarshal(data, &s); err != nil { return fmt.Errorf("{{$typename}} should be a string, got %s", data)