如何阻止json.Marshal转义<和&gt ;? [英] How to stop json.Marshal from escaping < and >?

查看:377
本文介绍了如何阻止json.Marshal转义<和&gt ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

package main

import "fmt"
import "encoding/json"

type Track struct {
    XmlRequest string `json:"xmlRequest"`
}

func main() {
    message := new(Track)
    message.XmlRequest = "<car><mirror>XML</mirror></car>"
    fmt.Println("Before Marshal", message)
    messageJSON, _ := json.Marshal(message)
    fmt.Println("After marshal", string(messageJSON))
}

是否可以使json.Marshal不逃避<>?我目前得到:

Is it possible to make json.Marshal not escape < and >? I currently get:

{"xmlRequest":"\u003ccar\u003e\u003cmirror\u003eXML\u003c/mirror\u003e\u003c/car\u003e"}

但是我正在寻找这样的东西:

but I am looking for something like this:

{"xmlRequest":"<car><mirror>XML</mirror></car>"}

推荐答案

从1.7版开始,您仍然无法使用json.Marshal()执行此操作. json.Marshal的源代码显示:

As of Go 1.7, you still cannot do this with json.Marshal(). The source code for json.Marshal shows:

> err := e.marshal(v, encOpts{escapeHTML: true})

json.Marshal始终这样做的原因是:

The reason json.Marshal always does this is:

字符串值编码为强制为有效UTF-8的JSON字符串, 用Unicode替换符文替换无效字节. 尖括号<"和>"转义为"\ u003c"和"\ u003e" 以防止某些浏览器将JSON输出误解为HTML. &符&"出于同样的原因也被转义到"\ u0026".

String values encode as JSON strings coerced to valid UTF-8, replacing invalid bytes with the Unicode replacement rune. The angle brackets "<" and ">" are escaped to "\u003c" and "\u003e" to keep some browsers from misinterpreting JSON output as HTML. Ampersand "&" is also escaped to "\u0026" for the same reason.

这意味着您甚至无法通过编写自定义func (t *Track) MarshalJSON()来做到这一点,您必须使用不符合 json.Marshaler 接口.

This means you cannot even do it by writing a custom func (t *Track) MarshalJSON(), you have to use something that does not satisfy the json.Marshaler interface.

因此,解决方法是编写自己的函数:

So, the workaround, is to write your own function:

func (t *Track) JSON() ([]byte, error) {
    buffer := &bytes.Buffer{}
    encoder := json.NewEncoder(buffer)
    encoder.SetEscapeHTML(false)
    err := encoder.Encode(t)
    return buffer.Bytes(), err
}

https://play.golang.org/p/FAH-XS-QMC

如果您想为任何结构提供通用解决方案,则可以执行以下操作:

If you want a generic solution for any struct, you could do:

func JSONMarshal(t interface{}) ([]byte, error) {
    buffer := &bytes.Buffer{}
    encoder := json.NewEncoder(buffer)
    encoder.SetEscapeHTML(false)
    err := encoder.Encode(t)
    return buffer.Bytes(), err
}

https://play.golang.org/p/bdqv3TUGr3

这篇关于如何阻止json.Marshal转义&lt;和&gt ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆