备忘:解决Golang字符串包含HTML序列化Json时出现Unicode编码


原文地址声明: https://blog.csdn.net/qq_23179075/article/details/113629747

在需要序列化的结构体或者map中有HTML字符串时,用常规的序列化方法会出现如下情况:

func TestA(t *testing.T) {
    data := map[string]string{
        "?9<>><9:>?8=19=0??0?": ">8=??我爱你=8;?>9<08<1>>1>",
    }
    x, _ := json.Marshal(data)
    fmt.Println(string(x))
}

输出结果:

{"?9\u003c\u003e\u003e\u003c9:\u003e?8=19=0??0?":"\u003e8=??我爱你=8;?\u003e9\u003c08\u003c1\u003e\u003e1\u003e"}

解决:


func TestB(t *testing.T) {
    data := map[string]string{
    "?9<>><9:>?8=19=0??0?": ">8=??我爱你=8;?>9<08<1>>1>",
    }
    buff := &bytes.Buffer{}
    encoder := json.NewEncoder(buff)
    encoder.SetEscapeHTML(false)
    err := encoder.Encode(data)
    fmt.Println(buff.String(),err)
}

输出结果:

{"?9<>><9:>?8=19=0??0?":">8=??我爱你=8;?>9<08<1>>1>"}