1 回答

TA貢獻(xiàn)1830條經(jīng)驗(yàn) 獲得超9個(gè)贊
不需要為狗和貓分別創(chuàng)建json對(duì)象。這將導(dǎo)致在編組數(shù)據(jù)時(shí)產(chǎn)生單獨(dú)的 json 對(duì)象。
您嘗試的方法基本上是適當(dāng)且無(wú)用的。
方法應(yīng)該創(chuàng)建一個(gè)結(jié)果結(jié)構(gòu),它將 dogs 和 cats 結(jié)構(gòu)作為字段,類型分別作為它們的切片。舉個(gè)例子:
package main
import (
? ? "fmt"
? ? "encoding/json"
? ? "log"
)
type Result struct{
? ? Dog []Dog
? ? Cat []Cat
}
type Dog struct{
? ?Breed string
? ?Color string
}
type Cat struct {
? ?Breed string
? ?Color string
}
func main(){
? ?dogs := []Dog{
? ? ? ?{"Chihuahua", "brown"},
? ? ? ?{"Pug", "white"},
? ?}
? ?cats := []Cat{
? ? ? ? {"British", "white"},
? ? ? ? {"Ragdoll", "gray"},
? ?}
? ?result := Result{
? ? Dog: dogs,
? ? Cat: cats,
? ?}?
? ?output, err := json.MarshalIndent(result, "", "\t")
? ?if err != nil {
? ? ? ?log.Fatal(err)
? ?}
? ?fmt.Println(string(output))
}
輸出:
{
? ? "Dog": [
? ? ? ? {
? ? ? ? ? ? "Breed": "Chihuahua",
? ? ? ? ? ? "Color": "brown"
? ? ? ? },
? ? ? ? {
? ? ? ? ? ? "Breed": "Pug",
? ? ? ? ? ? "Color": "white"
? ? ? ? }
? ? ],
? ? "Cat": [
? ? ? ? {
? ? ? ? ? ? "Breed": "British",
? ? ? ? ? ? "Color": "white"
? ? ? ? },
? ? ? ? {
? ? ? ? ? ? "Breed": "Ragdoll",
? ? ? ? ? ? "Color": "gray"
? ? ? ? }
? ? ]
}
- 1 回答
- 0 關(guān)注
- 120 瀏覽
添加回答
舉報(bào)