Skip to content

Commit 9538ff6

Browse files
authored
feat: DID JSON marshaller (#54)
Adds JSON marshal and unmarshal methods to DID type.
1 parent 75b1106 commit 9538ff6

2 files changed

Lines changed: 60 additions & 0 deletions

File tree

did/did.go

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package did
22

33
import (
4+
"encoding/json"
45
"fmt"
56
"strings"
67

@@ -55,6 +56,30 @@ func (d DID) GoString() string {
5556
return d.String()
5657
}
5758

59+
func (d DID) MarshalJSON() ([]byte, error) {
60+
if d == Undef {
61+
return json.Marshal(nil)
62+
}
63+
return json.Marshal(d.String())
64+
}
65+
66+
func (d *DID) UnmarshalJSON(b []byte) error {
67+
var str string
68+
err := json.Unmarshal(b, &str)
69+
if err != nil {
70+
return fmt.Errorf("parsing string: %w", err)
71+
}
72+
if str == "" {
73+
return nil
74+
}
75+
parsed, err := Parse(str)
76+
if err != nil {
77+
return fmt.Errorf("parsing DID: %w", err)
78+
}
79+
*d = parsed
80+
return nil
81+
}
82+
5883
func Decode(bytes []byte) (DID, error) {
5984
code, _, err := varint.FromUvarint(bytes)
6085
if err != nil {

did/did_test.go

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
package did
22

33
import (
4+
"encoding/json"
45
"testing"
6+
7+
"github.com/stretchr/testify/require"
58
)
69

710
func TestParseDIDKey(t *testing.T) {
@@ -77,3 +80,35 @@ func TestEquivalence(t *testing.T) {
7780
t.Fatalf("two equivalent DID not equivalent")
7881
}
7982
}
83+
84+
func TestRoundtripJSON(t *testing.T) {
85+
id, err := Parse("did:key:z6Mkod5Jr3yd5SC7UDueqK4dAAw5xYJYjksy722tA9Boxc4z")
86+
require.NoError(t, err)
87+
88+
type Object struct {
89+
ID DID `json:"id"`
90+
UndefID DID `json:"undef_id"`
91+
OptionalPresentID *DID `json:"optional_present_id"`
92+
OptionalAbsentID *DID `json:"optional_absent_id"`
93+
}
94+
obj := Object{
95+
ID: id,
96+
UndefID: Undef,
97+
OptionalPresentID: &id,
98+
OptionalAbsentID: nil,
99+
}
100+
101+
data, err := json.Marshal(obj)
102+
require.NoError(t, err)
103+
104+
t.Log(string(data))
105+
106+
var out Object
107+
err = json.Unmarshal(data, &out)
108+
require.NoError(t, err)
109+
110+
require.Equal(t, obj.ID, out.ID)
111+
require.Equal(t, obj.UndefID, out.UndefID)
112+
require.Equal(t, obj.OptionalPresentID.String(), out.OptionalPresentID.String())
113+
require.Nil(t, out.OptionalAbsentID)
114+
}

0 commit comments

Comments
 (0)