Merge PR #4454: Implement MarshalJSON for Coins Type
This commit is contained in:
parent
d204afbdae
commit
6ec9b26cef
|
@ -0,0 +1,2 @@
|
||||||
|
#4259 `Coins` that are `nil` are now JSON encoded as an empty array `[]`.
|
||||||
|
Decoding remains unchanged and behavior is left intact.
|
|
@ -1,6 +1,7 @@
|
||||||
package types
|
package types
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"regexp"
|
"regexp"
|
||||||
"sort"
|
"sort"
|
||||||
|
@ -151,6 +152,18 @@ func NewCoins(coins ...Coin) Coins {
|
||||||
return newCoins
|
return newCoins
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type coinsJSON Coins
|
||||||
|
|
||||||
|
// MarshalJSON implements a custom JSON marshaller for the Coins type to allow
|
||||||
|
// nil Coins to be encoded as an empty array.
|
||||||
|
func (coins Coins) MarshalJSON() ([]byte, error) {
|
||||||
|
if coins == nil {
|
||||||
|
return json.Marshal(coinsJSON(Coins{}))
|
||||||
|
}
|
||||||
|
|
||||||
|
return json.Marshal(coinsJSON(coins))
|
||||||
|
}
|
||||||
|
|
||||||
func (coins Coins) String() string {
|
func (coins Coins) String() string {
|
||||||
if len(coins) == 0 {
|
if len(coins) == 0 {
|
||||||
return ""
|
return ""
|
||||||
|
|
|
@ -4,6 +4,7 @@ import (
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/cosmos/cosmos-sdk/codec"
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
"github.com/stretchr/testify/require"
|
"github.com/stretchr/testify/require"
|
||||||
)
|
)
|
||||||
|
@ -621,3 +622,35 @@ func TestFindDup(t *testing.T) {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestMarshalJSONCoins(t *testing.T) {
|
||||||
|
cdc := codec.New()
|
||||||
|
RegisterCodec(cdc)
|
||||||
|
|
||||||
|
testCases := []struct {
|
||||||
|
name string
|
||||||
|
input Coins
|
||||||
|
strOutput string
|
||||||
|
}{
|
||||||
|
{"nil coins", nil, `[]`},
|
||||||
|
{"empty coins", Coins{}, `[]`},
|
||||||
|
{"non-empty coins", NewCoins(NewInt64Coin("foo", 50)), `[{"denom":"foo","amount":"50"}]`},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tc := range testCases {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
bz, err := cdc.MarshalJSON(tc.input)
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.Equal(t, tc.strOutput, string(bz))
|
||||||
|
|
||||||
|
var newCoins Coins
|
||||||
|
require.NoError(t, cdc.UnmarshalJSON(bz, &newCoins))
|
||||||
|
|
||||||
|
if tc.input.Empty() {
|
||||||
|
require.Nil(t, newCoins)
|
||||||
|
} else {
|
||||||
|
require.Equal(t, tc.input, newCoins)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
Loading…
Reference in New Issue