【问题标题】:How can I create a nested json structure including a []byte type?如何创建包含 []byte 类型的嵌套 json 结构?
【发布时间】:2019-10-18 05:43:37
【问题描述】:

我目前正在尝试创建以下嵌套 json,包括使用 golang 的证书的 json 和 DER 编码字节数组 () 列表:

{
"webhooks":
    [{
    "clientConfig":{
         "caBundle":"<derData []bytes>"
    },
    "name":"sth_name"
    }]
}

因为&lt;certDerBytes[]&gt;,需要用到一个struct,但是不知道怎么初始化。 到目前为止,我已经创建了结构:

type jsonstruct struct {
    Webhooks []struct {
        ClientConfig struct {
            CaBundle string `json:"caBundle"`
        } `json:"clientConfig"`
        Name string `json:"name"`
    } `json:"webhooks"`
}

但无法实例化我必须编组为 json 的结构。

我已经尝试过使用字符串字面量,有很多初始化它的方法,就像你对普通的非嵌套结构一样。

我还划分了结构,即 type jsonstruct.. type webhooks ... 等,但这是错误的。

我也从内到外初始化了结构,但也没有用。

我需要创建

【问题讨论】:

  • 请显示您尝试的实际代码以及遇到的具体问题。

标签: json go ssl-certificate


【解决方案1】:

您最好在字节数组本身上使用base64,并将其作为结构字段的有效负载。

一件傻事,我个人不喜欢嵌套的命名结构。将它们分开可以让您在代码中拥有更大的灵活性。

例如:

type jsonstruct struct {
    Webhooks []Webhook `json:"webhooks"`
}

type Webhook struct {
    ClientConfig ClientConfig `json:"clientConfig"`
    Name string `json:"name"`
}

type ClientConfig struct {
    CaBundle string `json:"caBundle"`
}

func (cc ClientConfig) ToBytes() []byte {
    return []byte(base64.StdEncoding.DecodeString(cc.CaBundle))
}

func (cc ClientConfig) FromBytes(cert []byte) {
    cc.CaBundle = base64.StdEncoding.EncodeToString(cert)
}

【讨论】:

  • 谢谢!作品。您是否有理由建议在 base64 中编码字节数组?
  • JSON 不支持本机二进制或字节数据。因此,我们需要将字节字符串转换为数据的字符串表示形式。如果我们只在 byte[] 数组周围使用 strings(),我们可能会超出不符合 JSON 规范的绑定 ASCII 字符(奇怪的字符,如 等)。 Base64 编码可确保我们的数据不会违反 JSON 有效负载中的预期字符。
  • 明白了。谢谢你的详细解释!
猜你喜欢
  • 2017-12-14
  • 1970-01-01
  • 2015-01-27
  • 2014-11-24
  • 2022-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-01
相关资源
最近更新 更多