[转载]golang json.Marshal 特殊html字符被转义解决方案

go语言提供了json的编解码包,json字符串作为参数值传输时发现,json.Marshal生成json特殊字符<、>、&会被转义。

type Test struct {
    Content     string
}
func main() {
    t := new(Test)
    t.Content = "http://www.baidu.com?id=123&test=1"
    jsonByte, _ := json.Marshal(t)
    fmt.Println(string(jsonByte))
}

{"Content":"http://www.baidu.com?id=123\u0026test=1"}
Process finished with exit code 0
 
GoDoc描述
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 escaping can be disabled using an Encoder that had SetEscapeHTML(false) alled on it.

json.Marshal 默认 escapeHtml 为true,会转义 <、>、&

func Marshal(v interface{}) ([]byte, error) {
    e := &encodeState{}
    err := e.marshal(v, encOpts{escapeHTML: true})
    if err != nil {
        return nil, err
    }
    return e.Bytes(), nil
}

解决方案
方法一:
content = strings.Replace(content, "\\u003c", "<", -1)
content = strings.Replace(content, "\\u003e", ">", -1)
content = strings.Replace(content, "\\u0026", "&", -1)

这种方式比较直接,硬性字符串替换。比较憨厚

方法二:
文档中写到This escaping can be disabled using an Encoder that had SetEscapeHTML(false) alled on it.

我们先创建一个buffer用于存储json
创建一个jsonencoder
设置html编码为false
type Test struct {
    Content     string
}
func main() {
    t := new(Test)
    t.Content = "http://www.baidu.com?id=123&test=1"
    bf := bytes.NewBuffer([]byte{})
    jsonEncoder := json.NewEncoder(bf)
    jsonEncoder.SetEscapeHTML(false)
    jsonEncoder.Encode(t)
    fmt.Println(bf.String())
}

{"Content":"http://www.baidu.com?id=123&test=1"}
Process finished with exit code 0

查看文档和源码还是解决问题的好方法
--------------------- 
作者:李浩的life 
来源:CSDN 
原文:https://blog.csdn.net/lihao19910921/article/details/81534286 
版权声明:本文为博主原创文章,转载请附上博文链接!

 

type EncodeResponse struct {
   Code    int                         `json:"code"`
   Message string                      `json:"message"`
   Data    []*common.AesEncodeResponse `json:"data"`
}
func convToJsonBytes(res *EncodeResponse) []byte {
   bf := bytes.NewBuffer([]byte{})
   jsonEncoder := json.NewEncoder(bf)
   jsonEncoder.SetEscapeHTML(false)
   jsonEncoder.Encode(res)
   glog.Infof("JSON Set false html escape. Res : %#v", res.Data)
   glog.Infof("JSON Set false html escape. buffer String: %#v", bf.String())
   glog.Infof("JSON Set false html escape. buffer bytes to String: %#v", bf.String())
   return bf.Bytes()
}

 

 

 

 

 

 

 

 

 

 

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值