diff --git a/angle.go b/angle.go index 99fd5f4..3d3eba6 100644 --- a/angle.go +++ b/angle.go @@ -2,6 +2,7 @@ package unit import ( "encoding" + "encoding/json" "fmt" "math" "strconv" @@ -87,3 +88,19 @@ func (a *Angle) UnmarshalString(s string) error { func (a *Angle) UnmarshalText(text []byte) error { return a.UnmarshalString(string(text)) } + +// UnmarshalJSON implements JSON unmarshalling for the Angle type. +// The type is represented as radians in JSON. +func (a *Angle) UnmarshalJSON(data []byte) error { + var angle float64 + err := json.Unmarshal(data, &angle) + if err != nil { + return err + } + *a = FromRadians(angle) + return nil +} + +func (a *Angle) MarshalJSON() ([]byte, error) { + return json.Marshal(a.Radians()) +} diff --git a/angle_test.go b/angle_test.go index 28fb910..c5e1e19 100644 --- a/angle_test.go +++ b/angle_test.go @@ -1,6 +1,7 @@ package unit import ( + "encoding/json" "math" "testing" @@ -97,3 +98,18 @@ func TestAngle_WrapZeroTwoPi(t *testing.T) { }) } } + +func TestAngle_JSON(t *testing.T) { + jsonString := "{\"TheImportantAngle\":0.786473}" + type JSONStruct struct { + TheImportantAngle Angle + } + var jsonStruct JSONStruct + err := json.Unmarshal([]byte(jsonString), &jsonStruct) + assert.NilError(t, err) + assert.Equal(t, jsonStruct.TheImportantAngle.Radians(), 0.786473) + + marshaled, err := json.Marshal(jsonStruct) + assert.NilError(t, err) + assert.Equal(t, string(marshaled), jsonString) +}