[#378] version: Add JSON encoding for Version type

Define `MarshalJSON` / `UnmarshalJSON` methods of the `Version` type.

Signed-off-by: Leonard Lyubich <ctulhurider@gmail.com>
This commit is contained in:
Leonard Lyubich 2023-01-31 12:18:45 +04:00
parent 8fdbf6950a
commit 651c17f9b3
2 changed files with 41 additions and 0 deletions

View file

@ -84,3 +84,29 @@ func (v Version) Equal(v2 Version) bool {
return v.Major() == v2.Major() &&
v.Minor() == v2.Minor()
}
// MarshalJSON encodes Version into a JSON format of the NeoFS API
// protocol (Protocol Buffers JSON).
//
// See also UnmarshalJSON.
func (v Version) MarshalJSON() ([]byte, error) {
var m refs.Version
v.WriteToV2(&m)
return m.MarshalJSON()
}
// UnmarshalJSON decodes NeoFS API protocol JSON format into the Version
// (Protocol Buffers JSON). Returns an error describing a format violation.
//
// See also MarshalJSON.
func (v *Version) UnmarshalJSON(data []byte) error {
var m refs.Version
err := m.UnmarshalJSON(data)
if err != nil {
return err
}
return v.ReadFromV2(m)
}

View file

@ -1,6 +1,7 @@
package version
import (
"math/rand"
"testing"
"github.com/nspcc-dev/neofs-api-go/v2/refs"
@ -48,3 +49,17 @@ func TestSDKVersion(t *testing.T) {
require.Equal(t, uint32(sdkMjr), v.Major())
require.Equal(t, uint32(sdkMnr), v.Minor())
}
func TestVersion_MarshalJSON(t *testing.T) {
var v Version
v.SetMajor(rand.Uint32())
v.SetMinor(rand.Uint32())
data, err := v.MarshalJSON()
require.NoError(t, err)
var v2 Version
require.NoError(t, v2.UnmarshalJSON(data))
require.Equal(t, v, v2)
}