diff --git a/cid.go b/cid.go index 99a26a6..ff3072c 100644 --- a/cid.go +++ b/cid.go @@ -410,7 +410,7 @@ func (c *Cid) UnmarshalJSON(b []byte) error { // // Note that this formatting comes from the IPLD specification // (https://github.com/ipld/specs/tree/master/ipld) -func (c *Cid) MarshalJSON() ([]byte, error) { +func (c Cid) MarshalJSON() ([]byte, error) { return []byte(fmt.Sprintf("{\"/\":\"%s\"}", c.String())), nil } diff --git a/cid_test.go b/cid_test.go index b7bdd89..3ecc7ef 100644 --- a/cid_test.go +++ b/cid_test.go @@ -383,3 +383,32 @@ func TestFromJson(t *testing.T) { t.Fatal("json parsing failed") } } + +func TestJsonRoundTrip(t *testing.T) { + exp, err := Decode("zb2rhhFAEMepUBbGyP1k8tGfz7BSciKXP6GHuUeUsJBaK6cqG") + if err != nil { + t.Fatal(err) + } + + // Verify it works for a *Cid. + enc, err := json.Marshal(exp) + if err != nil { + t.Fatal(err) + } + var actual Cid + err = json.Unmarshal(enc, &actual) + if !exp.Equals(&actual) { + t.Fatal("cids not equal for *Cid") + } + + // Verify it works for a Cid. + enc, err = json.Marshal(*exp) + if err != nil { + t.Fatal(err) + } + var actual2 Cid + err = json.Unmarshal(enc, &actual2) + if !(*exp).Equals(&actual2) { + t.Fatal("cids not equal for *Cid") + } +}