Skip to content

Commit

Permalink
add intbool type
Browse files Browse the repository at this point in the history
  • Loading branch information
kobtea committed Jan 22, 2017
1 parent 6393713 commit 6114ac0
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
25 changes: 25 additions & 0 deletions todoist/common.go
Original file line number Diff line number Diff line change
@@ -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
}
27 changes: 27 additions & 0 deletions todoist/common_test.go
Original file line number Diff line number Diff line change
@@ -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")
}
}

0 comments on commit 6114ac0

Please sign in to comment.