Skip to content

Commit

Permalink
Initial implementation of json point marshaling and unmarshalling
Browse files Browse the repository at this point in the history
  • Loading branch information
kellydunn committed Mar 18, 2014
1 parent a9d87bd commit 6cb5255
Show file tree
Hide file tree
Showing 4 changed files with 62 additions and 3 deletions.
2 changes: 1 addition & 1 deletion contour.go
Expand Up @@ -50,4 +50,4 @@ func (c Contour) Contains(p *Point) bool {
}

return intersections%2 != 0
}
}
29 changes: 29 additions & 0 deletions point.go
@@ -1,6 +1,10 @@
package geo

import (
"bytes"
"encoding/json"
"fmt"
"log"
"math"
)

Expand Down Expand Up @@ -93,3 +97,28 @@ func (p *Point) BearingTo(p2 *Point) float64 {

return brng
}

// Renders the current Point to valid JSON.
// Implements the json.Marshaller Interface.
func (p *Point) MarshalJSON() ([]byte, error) {
res := fmt.Sprintf(`{"lat":%v, "lng":%v}`, p.Lat(), p.Lng())
return []byte(res), nil
}

// Decodes the current Point from a JSON body.
// Throws an error if the body of the point cannot be interpreted by the JSON body
func (p *Point) UnmarshalJSON(data []byte) error {
// TODO throw an error if there is an issue parsing the body.
dec := json.NewDecoder(bytes.NewReader(data))
var values map[string]float64
err := dec.Decode(&values)

if err != nil {
log.Print(err)
return err
}

*p = *NewPoint(values["lat"], values["lng"])

return nil
}
30 changes: 30 additions & 0 deletions point_test.go
@@ -1,7 +1,9 @@
package geo

import (
"encoding/json"
"fmt"
"log"
"testing"
)

Expand Down Expand Up @@ -87,3 +89,31 @@ func TestBearingTo(t *testing.T) {
t.Error("Unnacceptable result.", fmt.Sprintf("%f", bearing))
}
}

func TestMarshalJSON(t *testing.T) {
p := NewPoint(40.7486, -73.9864)
res, err := json.Marshal(p)

if err != nil {
log.Print(err)
t.Error("Should not encounter an error when attempting to Marshal a Point to JSON")
}

if string(res) == "{lat:40.7486, lng:-73.9864}" {
t.Error("Point should correctly Marshal to JSON")
}
}

func TestUnmarshalJSON(t *testing.T) {
data := []byte(`{"lat":40.7486, "lng":-73.9864}`)
p := &Point{}
err := p.UnmarshalJSON(data)

if err != nil {
t.Errorf("Should not encounter an error when attempting to Unmarshal a Point from JSON")
}

if p.Lat() != 40.7486 || p.Lng() != -73.9864 {
t.Errorf("Point has mismatched data after Unmarshalling from JSON")
}
}
4 changes: 2 additions & 2 deletions polygon_test.go
Expand Up @@ -2,8 +2,8 @@ package geo

import (
"encoding/json"
"testing"
"os"
"testing"
)

// Tests a point is in a real geo polygon
Expand Down Expand Up @@ -91,4 +91,4 @@ func json2contour(filename string) (*Contour, error) {
cont.Add(np)
}
return cont, err
}
}

0 comments on commit 6cb5255

Please sign in to comment.