codes: fix: marshal/unmarshal a Code to JSON fails (#2116)
Marshalling a Code to JSON and unmarshalling it failed with an "invalid code" error message. Code is of type uint32. It has no custom MarshalJson() implemented therefore it is marshalled into an JSON integer value. The UnmarshalJSON() function expected that the marshalled Code is a String type, unmarshalling failed. Check in UnmarshalJSON() if the value is an uint32 in the range of the defined Code values. If it is, unmarshal it. This commit also adds an Marshal/Unmarshal testcase.
This commit is contained in:

committed by
Menghan Li

parent
590da37e2d
commit
b94ea975f3
@ -62,3 +62,23 @@ func TestUnmarshalJSON_UnknownInput(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnmarshalJSON_MarshalUnmarshal(t *testing.T) {
|
||||
for i := 0; i < _maxCode; i++ {
|
||||
var cUnMarshaled Code
|
||||
c := Code(i)
|
||||
|
||||
cJSON, err := json.Marshal(c)
|
||||
if err != nil {
|
||||
t.Errorf("marshalling %q failed: %v", c, err)
|
||||
}
|
||||
|
||||
if err := json.Unmarshal(cJSON, &cUnMarshaled); err != nil {
|
||||
t.Errorf("unmarshalling code failed: %s", err)
|
||||
}
|
||||
|
||||
if c != cUnMarshaled {
|
||||
t.Errorf("code is %q after marshalling/unmarshalling, expected %q", cUnMarshaled, c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user