gpt4 book ai didi

go - 用 jsonapi 编码(marshal) slice

转载 作者:IT王子 更新时间:2023-10-29 01:44:42 27 4
gpt4 key购买 nike

我有一片结构,我想使用 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}}}
}

但是,当我尝试对 slice 执行相同操作时,情况就大不相同了。

首先,我将我的 slice 转换为指向这些结构的指针 slice (不知道在这里还能做什么,将指针传递给 slice 没有用)。

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

但我确信一定有更好的方法,因此出现了这个问题。

最佳答案

想知道您能使用这样的东西吗??

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

关于go - 用 jsonapi 编码(marshal) slice ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45021734/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com