I have a slice of structs and I want to marshal it using https://github.com/google/jsonapi.
With a single struct, everything works fine. I simply pass a pointer as a second argument.
package main
import (
"fmt"
"os"
"github.com/google/jsonapi"
)
type Spider struct {
ID int `jsonapi:"primary,spiders"`
EyeCount int `jsonapi:"attr,eye_count"`
}
func main() {
jsonapi.MarshalPayload(os.Stdout, &Spider{ID: 2, EyeCount: 12})
// {"data":{"type":"spiders","id":"2","attributes":{"eye_count":12}}}
}
However, when I'm trying to do the same with a slice, things are quite different.
First of all, I'm converting my slice to a slice of pointers to those structs (don't know what else to do here, passing pointer to the slice didn't work).
spiders := []Spider{Spider{ID: 1, EyeCount: 8}, Spider{ID: 2, EyeCount: 12}}
var spiderPointers []*Spider
for _, x := range spiders {
spiderPointers = append(spiderPointers, &x)
}
jsonapi.MarshalPayload(os.Stdout, spiderPointers)
It works. Sort of. Here is the issue:
{"data":[
{"type":"spiders","id":"2","attributes":{"eye_count":12}},
{"type":"spiders","id":"2","attributes":{"eye_count":12}}]}
The last element is repeated and it replaces other elements.
In the end, I came up with a somewhat working solution:
spiders := []Spider{Spider{ID: 1, EyeCount: 8}, Spider{ID: 2, EyeCount: 12}}
var spiderPointers []interface{}
for _, x := range spiders {
var spider Spider
spider = x
spiderPointers = append(spiderPointers, &spider)
}
jsonapi.MarshalPayload(os.Stdout, spiderPointers)
// {"data":[{"type":"spiders","id":"1","attributes":{"eye_count":8}},
// {"type":"spiders","id":"2","attributes":{"eye_count":12}}]}
But I'm sure there must be a better way, hence this question.