From 30d27c305043b0505bcb1f85511445da42a4e802 Mon Sep 17 00:00:00 2001 From: Leonard Lyubich Date: Mon, 4 Jul 2022 12:24:38 +0300 Subject: [PATCH] [#289] oid: Add JSON encoding of `Address` type Signed-off-by: Leonard Lyubich --- object/id/address.go | 26 ++++++++++++++++++++++++++ object/id/address_test.go | 14 ++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/object/id/address.go b/object/id/address.go index 5cda2b07..3d34d1c8 100644 --- a/object/id/address.go +++ b/object/id/address.go @@ -65,6 +65,32 @@ func (x Address) WriteToV2(m *refs.Address) { m.SetContainerID(&cnr) } +// MarshalJSON encodes Address into a JSON format of the NeoFS API protocol +// (Protocol Buffers JSON). +// +// See also UnmarshalJSON. +func (x Address) MarshalJSON() ([]byte, error) { + var m refs.Address + x.WriteToV2(&m) + + return m.MarshalJSON() +} + +// UnmarshalJSON decodes NeoFS API protocol JSON format into the Address +// (Protocol Buffers JSON). Returns an error describing a format violation. +// +// See also MarshalJSON. +func (x *Address) UnmarshalJSON(data []byte) error { + var m refs.Address + + err := m.UnmarshalJSON(data) + if err != nil { + return err + } + + return x.ReadFromV2(m) +} + // Container returns unique identifier of the NeoFS object container. // // Zero Address has zero container ID, which is incorrect according to NeoFS diff --git a/object/id/address_test.go b/object/id/address_test.go index 322707a3..3c47cdbd 100644 --- a/object/id/address_test.go +++ b/object/id/address_test.go @@ -93,3 +93,17 @@ func TestAddress_DecodeString(t *testing.T) { require.Error(t, x2.DecodeString(strCnr+"\\"+strObj)) require.NoError(t, x2.DecodeString(strCnr+"/"+strObj)) } + +func TestAddressEncoding(t *testing.T) { + v := oidtest.Address() + + t.Run("json", func(t *testing.T) { + data, err := v.MarshalJSON() + require.NoError(t, err) + + var v2 oid.Address + require.NoError(t, v2.UnmarshalJSON(data)) + + require.Equal(t, v, v2) + }) +}