我想让一个json输出看起来像下图所示.注意,基于参数类型像 document
或 text
,接下来的关键变化是 document
或 text
.
"components": [
{
"type" : "header",
"parameters": [
{
"type": "document",
"document": {
"filename":"dummy.pdf",
"link": "https://en.unesco.org/inclusivepolicylab/sites/default/files/dummy-pdf_2.pdf"
}
}
]
},
{
"type" : "body",
"parameters": [
{
"type": "text",
"text": "replacement_text"
}
]
}
]
这是我的结构定义。
type Component struct {
Type string `json:"type,omitempty"`
Parameters []Parameter `json:"parameters,omitempty"`
}
type Parameter struct {
Type string `json:"type,omitempty"`
TypeInformation map[string]interface{}
}
当我对它进行编码时,它是这样的:
"components": [
{
"type": "body",
"parameters": [
{
"type": "text",
"TypeInformation": {
"text": "Param1"
}
},
{
"type": "text",
"TypeInformation": {
"text": "param2"
}
}
]
},
{
"type": "header",
"parameters": [
{
"type": "document",
"TypeInformation": {
"document": {
"link": "http://link",
"filename": "dummy.pdf"
}
}
}
]
}
]
我不想让 TypeInformation
键在json中出现,我只想要内部对象。我如何才能做到这一点?
而不是像你在使用 "通用 "结构时那样,使用一个任意的映射。Parameter
你可以为每个参数类型使用不同的具体类型。然后,只需将它们放入一片空的接口中,json.Marshal就会知道该怎么做。
type Object struct {
Components []Component `json:"components"`
}
type Component struct {
Type string `json:"type,omitempty"`
Parameters []interface{} `json:"parameters,omitempty"`
}
type TextParameter struct {
Type textType `json:"type"`
Text string `json:"text"`
}
type DocumentParameter struct {
Type documentType `json:"type"`
Document Document `json:"document"`
}
type Document struct {
FileName string `json:"filename"`
Link string `json:"link"`
}
// used to "hard code" the type of the parameter
type textType struct{}
func (textType) MarshalJSON() ([]byte, error) { return []byte(`"text"`), nil }
// used to "hard code" the type of the parameter
type documentType struct{}
func (documentType) MarshalJSON() ([]byte, error) { return []byte(`"document"`), nil }
然后你可以像这样初始化一个实例。
obj := Object{
Components: []Component{{
Type: "header",
Parameters: []interface{}{
DocumentParameter{Document: Document{
FileName: "dummy.pdf",
Link: "https://en.unesco.org/inclusivepolicylab/sites/default/files/dummy-pdf_2.pdf",
}},
},
}, {
Type: "body",
Parameters: []interface{}{
TextParameter{Text: "replacement_text"},
},
}},
}
如果默认的golang行为不合适,你可以自定义结构的marshalling行为。这可以通过实现 元帅 结构上的接口。
例子。
func (p Parameter) MarshalJSON() ([]byte, error) {
r := fmt.Sprintf(`{"type":"%v",`, p.Type)
switch p.Type {
case "document":
f := `"document":`
b, _ := json.Marshal(p.TypeInformation[p.Type])
r = r + f + string(b) + "}"
case "text":
f := `"text":`
b, _ := json.Marshal(p.TypeInformation[p.Type])
r = r + f + string(b) + "}"
}
return json.Marshal(r)
}
工作示例 此处