0

mochijson2:decode(<<"{\"strKey\":\"中国\", \"intKey\":10, \"arrayKey\":[1, 2, 3]}">>).

 ** 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)
4

1 回答 1

1

这不是 mochijson2 的错。/utf8当您通过 Erlang 控制台输入 utf8 二进制文件时,您必须通过在二进制文件末尾添加来明确告诉 shell 将其解释为 utf8 。如果你不这样做,它会尝试以某种奇怪的方式解释它。

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

只有在使用 Erlang shell 时才会出现问题。如果您将相同的二进制文件放入没有 . 的文件中/utf8,它将毫无问题地工作。

所以,在 Erlang shell 中,试试这个:

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]}]}
于 2014-08-29T07:11:43.133 回答