Skip to content

Commit

Permalink
feat(angle): implement JSON interface
Browse files Browse the repository at this point in the history
  • Loading branch information
hug-dev committed Jan 16, 2024
1 parent 79f3518 commit 919092a
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
17 changes: 17 additions & 0 deletions angle.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package unit

import (
"encoding"
"encoding/json"
"fmt"
"math"
"strconv"
Expand Down Expand Up @@ -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())
}
16 changes: 16 additions & 0 deletions angle_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package unit

import (
"encoding/json"
"math"
"testing"

Expand Down Expand Up @@ -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)
}

0 comments on commit 919092a

Please sign in to comment.