dqcqcqwq38860
dqcqcqwq38860
2016-05-31 19:50

Golang JSON封送将表情符号转换为问号

已采纳

I have a golang web server which communicates with a MySQL database. Users can post comments, and these comments can contain emoji, among other utf8mb4 characters. My database is capable of storing and retrieving these emoji characters, however, when JSON marshaling / unmarshmaling, emoji are mangled. Is is possible to use Go's native encoding/json package to decode / encode utf8mb4 characters? If so, how would I go about doing so. Thanks in advance!

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • doushaiyu5065 doushaiyu5065 5年前

    I was eventually able to find a workaround. Previously I was marshaling the JSON into a []byte and then calling w.Write(jsonBytes) on my http.ResponseWriter. By casting the bytes to a string, writing the appropriate content type header and using io.WriteString instead I was able to prevent the mangling. Here is my code:

    returnJSON, error := json.Marshal(value)
    if error != nil { Error(w, error); return }
    w.Header().Set("Content-Type", "application/json; charset=utf-8")
    io.WriteString(w, string(returnJSON))
    
    点赞 评论 复制链接分享