Commit 5fc52816 authored by Brendan O'Brien's avatar Brendan O'Brien Committed by Steven Allen

implement json.Umarshaler and json.Unmarshaler on datasetore.Key

parent 8b5f0c5d
package datastore
import (
"errors"
"path"
"strings"
......@@ -232,6 +233,23 @@ func (k Key) IsTopLevel() bool {
return len(k.List()) == 1
}
// MarshalJSON implements the json.Marshaler interface,
// keys are represented as JSON strings
func (k Key) MarshalJSON() ([]byte, error) {
return []byte(`"` + k.String() + `"`), nil
}
// MarshalJSON implements the json.Unmarshaler interface,
// keys will parse any value specified as a key to a string
func (k *Key) UnmarshalJSON(data []byte) error {
if len(data) < 2 {
k.Clean()
return errors.New("too short to unmarshal key to json string")
}
*k = NewKey(string(data[1 : len(data)-1]))
return nil
}
// RandomKey returns a randomly (uuid) generated key.
// RandomKey()
// NewKey("/f98719ea086343f7b71f32ea9d9d521d")
......
......@@ -155,3 +155,48 @@ func (ks *KeySuite) TestLess(c *C) {
checkLess("/a/b/c/d/e/f/g/h", "/b")
checkLess("/", "/a")
}
func TestKeyMarshalJSON(t *testing.T) {
cases := []struct {
key Key
data []byte
err string
}{
{NewKey("/a/b/c"), []byte("\"/a/b/c\""), ""},
}
for i, c := range cases {
out, err := c.key.MarshalJSON()
if !(err == nil && c.err == "" || err != nil && err.Error() == c.err) {
t.Errorf("case %d marshal error mismatch: expected: %s, got: %s", i, c.err, err)
}
if !bytes.Equal(c.data, out) {
t.Errorf("case %d value mismatch: expected: %s, got: %s", i, string(c.data), string(out))
}
}
}
func TestKeyUnmarshalJSON(t *testing.T) {
cases := []struct {
data []byte
key Key
err string
}{
{[]byte("\"/a/b/c\""), NewKey("/a/b/c"), ""},
{[]byte{}, NewKey("/"), "too short to unmarshal json string"},
{[]byte{'"'}, NewKey("/"), "too short to unmarshal json string"},
{[]byte(`""`), NewKey("/"), ""},
}
for i, c := range cases {
key := Key{}
err := key.UnmarshalJSON(c.data)
if !(err == nil && c.err == "" || err != nil && err.Error() == c.err) {
t.Errorf("case %d marshal error mismatch: expected: %s, got: %s", i, c.err, err)
}
if !key.Equal(c.key) {
t.Errorf("case %d key mismatch: expected: %s, got: %s", i, c.key, key)
}
}
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment