使用自定义 MarshalJSON 方法替换 go 序列化中的字符

据我所知,我只是做了一个定制的MarshalJSON方法来替换这些字符:\u003c\u003ehttps ://go.dev/play/p/xJ-qcMN9QXl

在上面的示例中,我通过从包含相同字段的辅助结构发送到编组来编组类似的结构,最后一步是替换我实际需要的字段和返回。正如您在从MarshalJSON方法返回之前放置的打印中看到的那样,特殊字符被替换了,但是在调用json.Marshalfunc 之后,特殊字符保持不变。

我在这里缺少但无法弄清楚的东西。感谢你的帮助。谢谢 :)


蛊毒传说
浏览 154回答 1
1回答

四季花海

在Marshaljson 包的文档中https://pkg.go.dev/encoding/json#Marshal你会发现以下段落:字符串值编码为强制为有效 UTF-8 的 JSON 字符串,用 Unicode 替换符文替换无效字节。为了将 JSON 安全地嵌入到 HTML 标签中,字符串使用 HTMLEscape 编码,它替换了“<”、“>”、“&”,U+2028 和 U+2029 被转义为“\u003c”, “\u003e”、“\u0026”、“\u2028”和“\u2029”。使用编码器时,可以通过调用 SetEscapeHTML(false) 禁用此替换。因此,请尝试使用Encoder, 示例:package mainimport (&nbsp; &nbsp; "bytes"&nbsp; &nbsp; "encoding/json"&nbsp; &nbsp; "fmt")type Foo struct {&nbsp; &nbsp; Name&nbsp; &nbsp; string&nbsp; &nbsp; Surname string&nbsp; &nbsp; Likes&nbsp; &nbsp;map[string]interface{}&nbsp; &nbsp; Hates&nbsp; &nbsp;map[string]interface{}&nbsp; &nbsp; newGuy&nbsp; bool //rpcclonable}func main() {&nbsp; &nbsp; foo := &Foo{&nbsp; &nbsp; &nbsp; &nbsp; Name:&nbsp; &nbsp; "George",&nbsp; &nbsp; &nbsp; &nbsp; Surname: "Denkin",&nbsp; &nbsp; &nbsp; &nbsp; Likes: map[string]interface{}{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "Sports":&nbsp; "volleyball",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "Message": "<Geroge> play volleyball <usually>",&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; }&nbsp; &nbsp; buf := &bytes.Buffer{} // or &strings.Builder{} as from the example of @mkopriva&nbsp; &nbsp; enc := json.NewEncoder(buf)&nbsp; &nbsp; enc.SetEscapeHTML(false)&nbsp; &nbsp; err := enc.Encode(foo)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Println(buf.String())}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go