donkey111111 2019-02-20 21:10
浏览 44

内部具有不同结构的类型结构切片

I'm trying to create the following json below, but I'm not getting it:

json

{
  "richResponse": {
    "items": [
      {
        "simpleResponse": {
          "textToSpeech": "foo1",
          "displayText": "foo2"
        }
      },
      {
        "basicCard": {
          "formattedText": "foo3",
          "imageDisplayOptions": "CROPPED"
        }
      }
    ]
  }
}

The problem is that I have a []struct calledItems (slice of structs) and it has 2 different structs SimpleResponse andBasicCard and I am not able to mount this json.

The errors appear:

can not use literal SimpleResponse

can not use BasicCard literal

main.go

https://play.golang.org/p/Gbl0UNWhqko

package main

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

func main() {

    type SimpleResponse struct {
        TextToSpeech string `json:"textToSpeech"`
        DisplayText  string `json:"displayText"`
    }

    type BasicCard struct {
        FormattedText       string `json:"formattedText"`
        ImageDisplayOptions string `json:"imageDisplayOptions"`
    }

    type Items []struct {
        SimpleResponse SimpleResponse `json:"simpleResponse"`
        BasicCard BasicCard `json:"basicCard"`
    }

    type RichResponse struct{
        Items Items `json:"items"`
    }

    group := RichResponse{  
        Items: Items{
            SimpleResponse{"foo1", "foo2"},
            BasicCard{
                FormattedText: "foo3",
                ImageDisplayOptions: "CROPPED",
            },
        },
    }

    b, err := json.Marshal(group)
    if err != nil {
        fmt.Println("error:", err)
    }
    os.Stdout.Write(b)
}

Could you help me mount this json?

  • 写回答

1条回答 默认 最新

  • duanci9305 2019-02-20 21:20
    关注

    Items is a slice of structs but you're using it as if it's a single Item struct. Being a slice with elements of type Item the correct syntax would be:

    group := RichResponse{  
        Items: Items{ // This is a slice
            Item{ // This is an element in the slice
                SimpleResponse{"foo1", "foo2"},
                BasicCard{
                    FormattedText: "foo3",
                    ImageDisplayOptions: "CROPPED",
                },
            },
        },
    }
    

    Note that you need to define Item as a named type if you don't want some really messy struct literals. Here's a working example on Playground: https://play.golang.org/p/pzO_w2cIeOJ

    评论

报告相同问题?

悬赏问题

  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥30 用arduino开发esp32控制ps2手柄一直报错
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 求chat4.0解答一道线性规划题,用lingo编程运行,第一问要求写出数学模型和lingo语言编程模型,第二问第三问解答就行,我的ddl要到了谁来求了
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题