Skip to content

Instantly share code, notes, and snippets.

@senid231
Created April 17, 2017 11:38
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 senid231/cdc14467b99da08b3b5eb6383dd1fd1a to your computer and use it in GitHub Desktop.
Save senid231/cdc14467b99da08b3b5eb6383dd1fd1a to your computer and use it in GitHub Desktop.
testing github.com/google/jsonapi - relation's attributes not populated from included data
package main
import (
"bytes"
"encoding/json"
"fmt"
"github.com/google/jsonapi"
)
type Author struct {
ID string `jsonapi:"primary,authors"`
FirstName string `jsonapi:"attr,first_name"`
LastName string `jsonapi:"attr,last_name"`
Posts []*Post `jsonapi:"relation,posts"`
}
type Post struct {
ID string `jsonapi:"primary,posts"`
Title string `jsonapi:"attr,title"`
Text string `jsonapi:"attr,text"`
}
func logError(err error) {
if err != nil {
fmt.Print("[Error] ")
fmt.Println(err)
}
}
func main() {
authorJsonApi := []byte(`{
"data": {
"id":"123",
"type":"authors",
"attributes": {
"first_name": "John",
"last_name": "Doe"
},
"relationships": {
"posts": {
"data": [{
"id": "456",
"type": "posts"
}],
"links": {
"self": "http://example.com/api/authors/123/posts",
"related": "http://example.com/api/authors/123/relationships/posts"
}
}
},
"links": {
"self": "http://example.com/api/authors/123"
},
"meta": {
"includes": ["posts"],
"duration": 600
},
"included":[{
"id":"456",
"type":"posts",
"attributes": {
"title":"Foo",
"text":"bar baz boo!"
}
}]
}
}`)
fmt.Printf("%s\n", authorJsonApi)
reader := bytes.NewReader(authorJsonApi)
author := Author{}
logError(jsonapi.UnmarshalPayload(reader, &author))
fmt.Printf("%#v\n", author)
fmt.Printf("%#v\n", *author.Posts[0])
aJsonApi, err := jsonapi.MarshalOne(&author)
logError(err)
aJson, err := json.Marshal(&aJsonApi)
logError(err)
fmt.Printf("%s\n", aJson)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment