与jsonapi的元帅切片

时间:2017-07-10 21:17:31

标签: go

我有一些结构,我想用https://github.com/google/jsonapi封送它。

使用单个结构,一切正常。我只是将指针作为第二个参数传递。

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

但是,当我尝试用切片做同样的事情时,事情就完全不同了。

首先,我将我的切片转换为指向那些结构的指针(不知道在这里做了什么,将指针传递给切片并不起作用)。 / p>

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)

有效。有点。这是问题所在:

{"data":[
  {"type":"spiders","id":"2","attributes":{"eye_count":12}},
  {"type":"spiders","id":"2","attributes":{"eye_count":12}}]}

重复最后一个元素,它取代了其他元素。

最后,我想出了一个有点工作的解决方案:

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

但我确信必须有更好的方法,因此这个问题。

2 个答案:

答案 0 :(得分:1)

好奇你能用这样的东西??

package main

import (
    "encoding/json"
    "fmt"
    "os"

    "github.com/google/jsonapi"
)

type Spider struct {
    ID       int `jsonapi:"primary,spiders"`
    EyeCount int `jsonapi:"attr,eye_count"`
}

func main() {
    // spiders is a slice of interfaces.. they can be unmarshalled back to spiders later if the need arises
    // you don't need a loop to create pointers either... so better in memory usage and a bit cleaner to read.. you can in theory load the []interface{} with a for loop as well since you mentioned getting this data from a db
    var spiders []interface{}
    spiders = append(spiders, &Spider{ID: 1, EyeCount: 8}, &Spider{ID: 2, EyeCount: 12})
    fmt.Println("jsonapi, MarshalPayload")
    jsonapi.MarshalPayload(os.Stdout, spiders)

    // test against marshall indent for sanity checking
    b, _ := json.MarshalIndent(spiders, "", " ")
    fmt.Println("marshall indent")
    fmt.Println(string(b))
}

答案 1 :(得分:0)

为什么不那样[是3]?

var spiders interface{}
db.Model(spiders).Select()
jsonapi.MarshalPayload(os.Stdout, spiders)