如何使用结构构建以下 JSON 对象

How to build the following JSON object using structs

我正在尝试使用 Golang 应用程序开发 Telegram Bot,我需要在用户启动与我的 bot 应用程序的会话后请求他们的联系信息。

要做到这一点,我们必须向 Telegram API 发送一个 http 请求,其中包含以下类型的 JSON 正文。我不知道如何使用结构和 JSON.Marshal 方法构建 JSON。有人可以帮我弄清楚吗?

{
    "chat_id": 774854789,
    "text": "message",
    "parse_mode": "markdown",
    "reply_markup": {
        "keyboard": [
            [{
                "text": "Send contact.",
                "request_contact": true,
                "request_location": false
            }]
        ],
        "resize_keyboard": true
    }
}

这是我需要使用结构构建的 JSON。

to Marshal struct to wanted json - 使用结构字段标签很好。非常基本的示例(有关更多信息,请阅读 https://golang.org/pkg/encoding/json/ ) and some info about structs tags https://www.digitalocean.com/community/tutorials/how-to-use-struct-tags-in-go:

package main

import (
    "encoding/json"
    "log"
)

type KeyboardStruct struct {
    Text            string `json:"text"`
    RequestContact  bool   `json:"request_contact"`
    RequestLocation bool   `json:"request_location"`
}

type ReplyMarkupStruct struct {
    Keyboard       [][]KeyboardStruct `json:"keyboard"`
    ResizeKeyboard bool               `json:"resize_keyboard"`
}

type ResponseStruct struct {
    ChatId      int               `json:"chat_id"`
    Text        string            `json:"text"`
    ParseMode  string            `json:"parse_mode"`
    ReplyMarkup ReplyMarkupStruct `json:"reply_markup"`
}

func main() {
    // Example 1.
    var res ResponseStruct
    // Make KeyboardStructs
    keyboard := [][]KeyboardStruct{
        {KeyboardStruct{
            Text:            "",
            RequestContact:  false,
            RequestLocation: false,
        }}}
    // Change in .ReplyMarkup.Keyboard
    res.ReplyMarkup.Keyboard = keyboard
    b, _ := json.Marshal(res)
    log.Println(string(b))

    // Example 2.
    keyboard2 := [][]KeyboardStruct{
        {KeyboardStruct{
            Text:            "",
            RequestContact:  true,
            RequestLocation: false,
        }}}
    res2 := ResponseStruct{ChatId: 123346, Text: "test", ReplyMarkup: ReplyMarkupStruct{
        keyboard2, true,
    }}
    b, _ = json.Marshal(res2)
    log.Println(string(b))
}