golang中json.marshal字符转义问题

最近在封装自定义json库,数据结构用自带的map,序列化接口调用了json.marshal去实现,发现&字符序列化之后变成了\u0026。

1、查阅了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) called on it.

也就是说json.marshal默认escapeHtml为true,会将<、>、&等字符转义。

godoc打开方式可参考如下:

1、直接在CMD下,运行godoc -http=:8080就可以了;
2、然后再浏览器上输入127.0.0.1:8080就可以访问本地的GO DOC文档库;

2、解决方案

package main

import (
	"bytes"
	"encoding/json"
	"fmt"
)

type MarshalTest struct {
	Url string `json:"url"`
}

//序列化
func marshal_inner(data interface{}) ([]byte, error) {
	bf := bytes.NewBuffer([]byte{})
	jsonEncoder := json.NewEncoder(bf)
	jsonEncoder.SetEscapeHTML(false)
	if err := jsonEncoder.Encode(data); err != nil {
		return nil, err
	}

	return bf.Bytes(), nil
}

func main() {
	t := &MarshalTest{
		Url: "http://www.baidu.com?seq=213&uuid=1",
	}
	val, err := marshal_inner(t)
	if err != nil {
		fmt.Println("marshal_inner failed.err:", err)
		return
	}
	fmt.Println("marshal_inner val:", string(val))
}

你可能感兴趣的:(golang中json.marshal字符转义问题)