golang转换包含unicode的字节数组

wor*_*ing 2 go

type MyStruct struct {
    Value json.RawMessage `json:"value"`
}

var resp *http.Response

if resp, err = http.DefaultClient.Do(req); err == nil {
    if resp.StatusCode == 200 {
        var buffer []byte
        if buffer, err = ioutil.ReadAll(resp.Body); err == nil {

            mystruct = &MyStruct{}
            err = json.Unmarshal(buffer, mystruct)

        }
    }
}

fmt.Println(string(mystruct.Value))
Run Code Online (Sandbox Code Playgroud)

它产生类似的东西:

   \u003Chead>\n  \u003C/head>\n  \u003Cbody>
Run Code Online (Sandbox Code Playgroud)

文档位于: http: //golang.org/pkg/encoding/json/#Unmarshal

说:当解组带引号的字符串时,无效的 UTF-8 或无效的 UTF-16 代理项对不会被视为错误。相反,它们被 Unicode 替换字符 U+FFFD 替换。

我想这就是正在发生的事情。我只是看不到答案,因为我对围棋的经验很少而且我很累。

Coc*_*nut 6

有一种方法可以将转义的 unicode 字符转换json.RawMessage为有效的 UTF8 字符,而无需对其进行解组。(因为我的主要语言是韩语,所以我必须处理这个问题。)

\n\n

您可以使用strconv.Quote()strconv.Unquote()进行转换。

\n\n
func _UnescapeUnicodeCharactersInJSON(_jsonRaw json.RawMessage) (json.RawMessage, error) {\n    str, err := strconv.Unquote(strings.Replace(strconv.Quote(string(_jsonRaw)), `\\\\u`, `\\u`, -1))\n    if err != nil {\n        return nil, err\n    }\n    return []byte(str), nil\n}\n\nfunc main() {\n    // Both are valid JSON.\n    var jsonRawEscaped json.RawMessage   // json raw with escaped unicode chars\n    var jsonRawUnescaped json.RawMessage // json raw with unescaped unicode chars\n\n    // \'\\u263a\' == \'\xe2\x98\xba\'\n    jsonRawEscaped = []byte(`{"HelloWorld": "\\uC548\\uB155, \\uC138\\uC0C1(\\u4E16\\u4E0A). \\u263a"}`) // "\\\\u263a"\n    jsonRawUnescaped, _ = _UnescapeUnicodeCharactersInJSON(jsonRawEscaped)                        // "\xe2\x98\xba"\n\n    fmt.Println(string(jsonRawEscaped))   // {"HelloWorld": "\\uC548\\uB155, \\uC138\\uC0C1(\\u4E16\\u4E0A). \\u263a"}\n    fmt.Println(string(jsonRawUnescaped)) // {"HelloWorld": "\xec\x95\x88\xeb\x85\x95, \xec\x84\xb8\xec\x83\x81(\xe4\xb8\x96\xe4\xb8\x8a). \xe2\x98\xba"}\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

https://play.golang.org/p/pUsrzrrcDG-

\n\n

希望这有帮助:D

\n