Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(angle): implement JSON interface #168

Merged
merged 1 commit into from
Jan 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 {
hug-dev marked this conversation as resolved.
Show resolved Hide resolved
var angle float64
err := json.Unmarshal(data, &angle)
if err != nil {
return err
}
*a = FromRadians(angle)
return nil
}

func (a *Angle) MarshalJSON() ([]byte, error) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missed the matching comment here too :)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since those are not meant to be called directly, I did not think this was very important. Can add one more PR either

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)
}