From b115c3ed64516169bdfdfa4e3b1e08d50ba6c20b Mon Sep 17 00:00:00 2001 From: Mike <41407352+hunjixin@users.noreply.github.com> Date: Tue, 11 Jan 2022 09:54:44 +0800 Subject: [PATCH] fix json marshal/unmarshal for FIL type (#4686) --- pkg/types/internal/fil.go | 22 ++++++++++++++++ pkg/types/internal/fil_test.go | 47 ++++++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+) diff --git a/pkg/types/internal/fil.go b/pkg/types/internal/fil.go index 3270a30eef..4209ea1ac0 100644 --- a/pkg/types/internal/fil.go +++ b/pkg/types/internal/fil.go @@ -2,6 +2,7 @@ package internal import ( "encoding" + "encoding/json" "fmt" fbig "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/venus/pkg/constants" @@ -85,6 +86,24 @@ func (f FIL) UnmarshalText(text []byte) error { return nil } +func (f FIL) MarshalJSON() ([]byte, error) { + return []byte("\"" + f.String() + "\""), nil +} + +func (f *FIL) UnmarshalJSON(by []byte) error { + p, err := ParseFIL(strings.Trim(string(by), "\"")) + if err != nil { + return err + } + if f.Int != nil { + f.Int.Set(p.Int) + } else { + f.Int = p.Int + } + + return nil +} + func ParseFIL(s string) (FIL, error) { suffix := strings.TrimLeft(s, "-.1234567890") s = s[:len(s)-len(suffix)] @@ -135,3 +154,6 @@ func MustParseFIL(s string) FIL { var _ encoding.TextMarshaler = (*FIL)(nil) var _ encoding.TextUnmarshaler = (*FIL)(nil) + +var _ json.Marshaler = (*FIL)(nil) +var _ json.Unmarshaler = (*FIL)(nil) diff --git a/pkg/types/internal/fil_test.go b/pkg/types/internal/fil_test.go index 95630a8a64..d21918a5be 100644 --- a/pkg/types/internal/fil_test.go +++ b/pkg/types/internal/fil_test.go @@ -1,6 +1,9 @@ package internal import ( + "encoding/json" + "fmt" + "math/big" "testing" "github.com/stretchr/testify/require" @@ -112,3 +115,47 @@ func TestFilShort(t *testing.T) { }) } } + +func TestMarshal(t *testing.T) { + type A struct { + Fil FIL + } + var a = A{ + Fil: FIL{big.NewInt(1000000)}, + } + + aBytes, err := json.Marshal(a) + require.NoError(t, err) + + require.Equal(t, aBytes, []byte("{\"Fil\":\"0.000000000001 FIL\"}")) + fmt.Println(string(aBytes)) +} + +func TestUnMarshal(t *testing.T) { + type A struct { + Fil FIL + } + bigFIl, _ := big.NewInt(0).SetString("100000000000000000000", 10) + for _, s := range []struct { + fil string + expect FIL + }{ + { + fil: "{\"Fil\":\"0.000000000001 FIL\"}", + expect: FIL{big.NewInt(1000000)}, + }, + { + fil: "{\"Fil\":\"1 FIL\"}", + expect: FIL{big.NewInt(1000000000000000000)}, + }, + { + fil: "{\"Fil\":\"100 FIL\"}", + expect: FIL{bigFIl}, + }, + } { + a := A{} + err := json.Unmarshal([]byte(s.fil), &a) + require.NoError(t, err) + require.Equal(t, a.Fil.String(), s.expect.String()) + } +}