diff --git a/todoist/common.go b/todoist/common.go new file mode 100644 index 0000000..842e935 --- /dev/null +++ b/todoist/common.go @@ -0,0 +1,25 @@ +package todoist + +import "fmt" + +type IntBool bool + +func (i IntBool) MarshalJSON() ([]byte, error) { + if i { + return []byte("1"), nil + } else { + return []byte("0"), nil + } +} + +func (i *IntBool) UnmarshalJSON(b []byte) (err error) { + switch string(b) { + case "1": + *i = true + case "0": + *i = false + default: + return fmt.Errorf("Could not unmarshal into intbool: %s", string(b)) + } + return nil +} diff --git a/todoist/common_test.go b/todoist/common_test.go new file mode 100644 index 0000000..3f36f41 --- /dev/null +++ b/todoist/common_test.go @@ -0,0 +1,27 @@ +package todoist + +import "testing" + +func TestIntBool_MarshalJSON(t *testing.T) { + s := "0" + v := IntBool(false) + b, err := v.MarshalJSON() + if err != nil || string(b) != s { + t.Errorf("Expect %s, but got %s", s, string(b)) + } +} + +func TestIntBool_UnmarshalJSON(t *testing.T) { + s := "0" + var v IntBool + err := v.UnmarshalJSON([]byte(s)) + if err != nil || v != IntBool(false) { + t.Errorf("Expect %s, but got %s", IntBool(false), v) + } + + s = "10" + err = v.UnmarshalJSON([]byte(s)) + if err == nil { + t.Error("Expect error, but no error") + } +}