Skip to content

Instantly share code, notes, and snippets.

@christianklotz
Created October 9, 2015 14:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save christianklotz/ac556f4037b13fc0dcf4 to your computer and use it in GitHub Desktop.
Save christianklotz/ac556f4037b13fc0dcf4 to your computer and use it in GitHub Desktop.
package main
import (
"database/sql"
"errors"
"fmt"
"strconv"
"github.com/manyminds/api2go/jsonapi"
)
var s = `{
"data": {
"type": "tickets",
"attributes": {
"number": "1234",
"exp_year": 2018,
"title": "Classical Concert"
},
"relationships": {
"address": {
"data": {
"type": "addresses",
"id": "2"
}
}
}
},
"included": [
{
"type": "addresses",
"id": "2",
"attributes":
{
"line1": "Lorem ipsum"
}
}
]
}`
type Address struct {
ID int `jsonapi:"-" gorm:"primary_key"`
Line1 string `jsonapi:"name=line1" gorm:"column:line1"`
Line2 string `jsonapi:"name=line2" gorm:"column:line2"`
City string `jsonapi:"name=city" gorm:"column:city"`
Region string `jsonapi:"name=region" gorm:"column:region"`
PostalCode string `jsonapi:"name=postal_code" gorm:"column:postal_code"`
CountryCode string `jsonapi:"name=country_code" gorm:"column:country_code"`
}
// GetID implements the MarshalIdentifier interface
func (a Address) GetID() string {
return strconv.Itoa(a.ID)
}
// SetID implements the UnmarshalIdentifier interface
func (a *Address) SetID(id string) error {
var err error
a.ID, err = strconv.Atoi(id)
return err
}
// GetName implements the EntityNamer interface
func (a Address) GetName() string {
return "addresses"
}
type ticket struct {
Number string `jsonapi:"name=number"`
Title string `jsonapi:"name=title"`
ExpiryYear int `jsonapi:"name=exp_year"`
DeliveryAddress Address `jsonapi:"name=address"`
DeliveryAddressID sql.NullInt64 `jsonapi:"-"`
}
func (t ticket) SetToOneReferenceID(name, ID string) error {
if name == "address" {
intID, err := strconv.ParseInt(ID, 10, 64)
if err != nil {
return err
}
t.DeliveryAddressID = sql.NullInt64{Valid: true, Int64: intID}
return nil
}
return errors.New("There is no to-one relationship named " + name)
}
func main() {
var c ticket
if err := jsonapi.UnmarshalFromJSON([]byte(s), &c); err != nil {
panic(err)
}
fmt.Println(c)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment