douyamitong57935 2015-02-18 23:04
浏览 231
已采纳

如何阻止json.Marshal转义<和>?

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

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>"}
  • 写回答

5条回答 默认 最新

  • dongye9453 2015-02-18 23:51
    关注

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

    The reason json.Marshal always does this is:

    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.

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?