2014-08-29 51 views
0

mochijson2解碼(< <「{\」strKey \「:\」中國\「,\」intKey \「:10,\」arrayKey \「:[1,2 ,3]}「>>)。mochijson2解碼中文有錯誤異常拋出:invalid_utf8

** exception throw: invalid_utf8 
    in function mochijson2:tokenize_string_fast/2 (src/mochijson2.erl, line 424) 
    in call from mochijson2:tokenize_string/2 (src/mochijson2.erl, line 391) 
    in call from mochijson2:decode1/2 (src/mochijson2.erl, line 326) 
    in call from mochijson2:decode_object/3 (src/mochijson2.erl, line 354) 
    in call from mochijson2:json_decode/2 (src/mochijson2.erl, line 321) 

回答

1

這不是mochijson2故障。 當您通過Erlang控制檯輸入utf8二進制文件時,必須明確告訴shell將其解釋爲utf8,方法是在二進制文件的末尾添加/utf8。如果你不這樣做,它會嘗試以一種奇怪的方式解釋它。

1> <<"中國">>. 
<<"-ý">> % wrong representation 
2> <<"中國"/utf8>>. 
<<228,184,173,229,155,189>> % ok representation 

只有使用Erlang shell時纔會出現問題。如果您將同一個二進制文件放在沒有/utf8的文件中,它將毫無問題地工作。

所以,在二郎殼,試試這個:

1> mochijson2:decode(<<"{\"strKey\":\"中國\", \"intKey\":10, \"arrayKey\":[1, 2, 3]}"/utf8>>). 
{struct,[{<<"strKey">>,<<228,184,173,229,155,189>>}, 
    {<<"intKey">>,10}, 
    {<<"arrayKey">>,[1,2,3]}]}