golang转换包含unicode的字节数组

时间:2015-03-27 15:26:47

标签: 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))

它产生类似的东西:

   \u003Chead>\n  \u003C/head>\n  \u003Cbody>

Doc at:http://golang.org/pkg/encoding/json/#Unmarshal

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

我认为这是正在发生的事情。我无法看到答案,因为我的经验很少,我很累。

2 个答案:

答案 0 :(得分:3)

您决定使用json.RawMessage来阻止在json消息中使用密钥value解析值。

字符串文字"\u003chtml\u003e""<html>"的有效json表示。

由于您告诉json.Unmarshal不解析此部分,因此它不解析它并按原样返回给您。

如果您想将其解析为UTF-8字符串,请将MyStruct的定义更改为:

type MyStruct struct {
    Value string `json:"value"`
}

答案 1 :(得分:1)

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

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

func _UnescapeUnicodeCharactersInJSON(_jsonRaw json.RawMessage) (json.RawMessage, error) {
    str, err := strconv.Unquote(strings.Replace(strconv.Quote(string(_jsonRaw)), `\\u`, `\u`, -1))
    if err != nil {
        return nil, err
    }
    return []byte(str), nil
}

func main() {
    // Both are valid JSON.
    var jsonRawEscaped json.RawMessage   // json raw with escaped unicode chars
    var jsonRawUnescaped json.RawMessage // json raw with unescaped unicode chars

    // '\u263a' == '☺'
    jsonRawEscaped = []byte(`{"HelloWorld": "\uC548\uB155, \uC138\uC0C1(\u4E16\u4E0A). \u263a"}`) // "\\u263a"
    jsonRawUnescaped, _ = _UnescapeUnicodeCharactersInJSON(jsonRawEscaped)                        // "☺"

    fmt.Println(string(jsonRawEscaped))   // {"HelloWorld": "\uC548\uB155, \uC138\uC0C1(\u4E16\u4E0A). \u263a"}
    fmt.Println(string(jsonRawUnescaped)) // {"HelloWorld": "안녕, 세상(世上). ☺"}
}

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

希望这会有所帮助:D