dqtl46964 2017-07-10 21:17
浏览 36

使用jsonapi的元帅切片

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.

  • 写回答

2条回答 默认 最新

  • donglangtun1850 2017-07-10 22:09
    关注

    Why not that way [either3]?

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

报告相同问题?

悬赏问题

  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题