我正在尝试将 JSON 解组到我的 Mail 结构,但 Go 在解析 html_tmpl 和 text_tmpl 字段时返回错误。我怎么解决这个问题?HtmlTmpl 字段来自:html, err := template.ParseFiles(pathToHTMLFile)这是您可以测试的基本示例package mainimport ( "encoding/json" "fmt" "html/template" "time")type Mail struct { Id string `json:"id"` Subject string `json:"subject"` From string `json:"from"` To string `json:"to"` Date time.Time `json:"date"` HtmlTmpl template.Template `json:"html_tmpl"` TextTmpl template.Template `json:"text_tmpl"` Context map[string]string `json:"context"`}func main() { mail := &Mail{} s := `{"id":"","subject":"Test mail","from":"support@example.com","to":"user@gmail.com","date":"0001-01-01T00:00:00Z","html_tmpl":{"Tree":{"Name":"template.html","ParseName":"template.html","Root":{"NodeType":11,"Pos":0,"Nodes":[{"NodeType":0,"Pos":0,"Text":"PCFET0NUWVBFIGh0bWw+CjxodG1sIGxhbmc9InJ1Ij4KPGhlYWQ+Cgk8bWV0YSBodHRwLWVxdWl2PSJDb250ZW50LVR5cGUiIGNvbnRlbnQ9InRleHQvaHRtbCIgY2hhcnNldD0iVVRGLTgiPgoJPG1ldGEgbmFtZT0idmlld3BvcnQiIGNvbnRlbnQ9IndpZHRoPWRldmljZS13aWR0aCwgaW5pdGlhbD0xIj4KCTxtZXRhIGh0dHAtZXF1aXY9IlgtVUEtQ29tcGF0aWJsZSIgY29udGVudD0iSUU9ZWRnZSI+Cgk8dGl0bGU+0J/RgNC+0LLQtdGA0LrQsCDRgdCy0Y/Qt9C4PC90aXRsZT4KPC9oZWFkPgo8Ym9keT4KCTxzcGFuPg=="},{"NodeType":1,"Pos":298,"Line":10,"Pipe":{"NodeType":14,"Pos":298,"Line":10,"IsAssign":false,"Decl":null,"Cmds":[{"NodeType":4,"Pos":298,"Args":[{"NodeType":8,"Pos":298,"Ident":["msg"]}]}]}},{"NodeType":0,"Pos":305,"Text":"PC9zcGFuPgo8L2JvZHk+CjwvaHRtbD4="}]}}},"text_tmpl":{"Tree":{"Name":"template.txt","ParseName":"template.txt","Root":{"NodeType":11,"Pos":0,"Nodes":[{"NodeType":1,"Pos":2,"Line":1,"Pipe":{"NodeType":14,"Pos":2,"Line":1,"IsAssign":false,"Decl":null,"Cmds":[{"NodeType":4,"Pos":2,"Args":[{"NodeType":8,"Pos":2,"Ident":["msg"]}]}]}}]}}},"context":{"msg":"Hi!"}}` err := json.Unmarshal([]byte(s), mail) fmt.Println(err) fmt.Println(mail)}
1 回答
芜湖不芜
TA贡献1796条经验 获得超7个赞
template.Template
不支持从 JSON 编组/解组。它是一个带有未导出字段的结构,并且它没有实现处理封送/解封逻辑的接口(例如json.Unmarshaler
)。
您应该做的是在您的 JSON 和结构中包含源模板文本,并在解组源模板文本后,将其解析为后处理步骤。如果你想编组一个包含模板的结构,它应该只包含源模板文本(template.Template
字段应该被标记为省略,如json:"-"
)。
- 1 回答
- 0 关注
- 152 浏览
添加回答
举报
0/150
提交
取消