我正在尝试使用simplejson和Json.NET在Python服务器和C#客户端之间建立一个非常基本的基于ZeroMQ的套接字链接。 我尝试从Python发送一个dict并将其读入C#中的一个对象。 Python代码:
message = {'MessageType':"None", 'ContentType':"None", 'Content':"OK"}
message_blob = simplejson.dumps(message).encode(encoding = "UTF-8")
alive_socket.send(message_blob)
邮件以普通的UTF-8字符串发送,如果我使用UTF-16,则发送为“'\ xff \ xfe {\ x00”\ x00 ...“等。
C#中的代码是我的问题所在:
string reply = client.Receive(Encoding.UTF8);
UTF-8消息收到“≻潃瑮湥≴> ...”等。
我尝试使用UTF-16并且消息通过OK,但是第一个符号仍然是little-endian \ xFF \ xFE BOM,因此当我尝试将其提供给反序列化器时,
PythonMessage replyMessage = JsonConvert.DeserializeObject<PythonMessage>(reply);
//PythonMessage is just a very simple class with properties,
//not relevant to the problem
我收到错误(显然出现在第一个符号,\ xFF):
Unexpected character encountered while parsing value: .
我使用编码的方式显然有些不对劲。你能告诉我正确的方法吗?
答案 0 :(得分:1)
UTF-16中必须使用字节顺序标记。您可以使用UTF-16LE或UTF-16BE来假设特定的字节顺序,并且不会生成BOM。也就是说,使用:
message_blob = simplejson.dumps(message).encode(encoding = "UTF-16le")