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 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计