gpt4 book ai didi

json - 如何创建包含 []byte 类型的嵌套 json 结构?

转载 作者:行者123 更新时间:2023-12-01 22:28:16 27 4
gpt4 key购买 nike

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

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

因为 <certDerBytes[]> ,我需要使用一个结构,但我不知道如何初始化它。
到目前为止,我已经创建了结构:
type jsonstruct struct {
Webhooks []struct {
ClientConfig struct {
CaBundle string `json:"caBundle"`
} `json:"clientConfig"`
Name string `json:"name"`
} `json:"webhooks"`
}

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

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

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

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

我需要创建

最佳答案

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

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

例如:

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

关于json - 如何创建包含 []byte 类型的嵌套 json 结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58440939/

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