Skip to content

Commit 36a8266

Browse files
authored
fix(scw): decimal json representation (scaleway#2235)
1 parent a80efc7 commit 36a8266

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

scw/custom_types.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -460,3 +460,24 @@ var _ fmt.Stringer = (*Decimal)(nil)
460460
func (d Decimal) String() string {
461461
return string(d)
462462
}
463+
464+
func (d Decimal) MarshalJSON() ([]byte, error) {
465+
return json.Marshal(map[string]interface{}{
466+
"value": d.String(),
467+
})
468+
}
469+
470+
func (d *Decimal) UnmarshalJSON(b []byte) error {
471+
m := struct {
472+
Value string `json:"value"`
473+
}{}
474+
475+
err := json.Unmarshal(b, &m)
476+
if err != nil {
477+
return err
478+
}
479+
480+
*d = Decimal(m.Value)
481+
482+
return nil
483+
}

scw/custom_types_test.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -841,3 +841,20 @@ func TestDecimal(t *testing.T) {
841841
*dPtr = "1.22"
842842
testhelpers.Equals(t, "1.22", dPtr.String())
843843
}
844+
845+
func TestDecimal_MarshalJSON(t *testing.T) {
846+
d := Decimal("1.22")
847+
testhelpers.Equals(t, "1.22", d.String())
848+
849+
value, err := json.Marshal(d)
850+
testhelpers.AssertNoError(t, err)
851+
testhelpers.Equals(t, "{\"value\":\"1.22\"}", string(value))
852+
}
853+
854+
func TestDecimal_UnmarshalJSON(t *testing.T) {
855+
value := "{\"value\":\"1.22\"}"
856+
d := new(Decimal)
857+
err := json.Unmarshal([]byte(value), d)
858+
testhelpers.AssertNoError(t, err)
859+
testhelpers.Equals(t, "1.22", d.String())
860+
}

0 commit comments

Comments
 (0)