我正在尝试使用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: .我正在使用编码的方式显然是错误的。 你能告诉我正确的方法吗?
I'm trying to set up a very basic ZeroMQ-based socket link between Python server and C# client using simplejson and Json.NET. I try to send a dict from Python and read it into an object in C#. Python code:
message = {'MessageType':"None", 'ContentType':"None", 'Content':"OK"} message_blob = simplejson.dumps(message).encode(encoding = "UTF-8") alive_socket.send(message_blob)The message is sent as normal UTF-8 string or, if I use UTF-16, as "'\xff\xfe{\x00"\x00..." etc.
Code in C# is where my problem is:
string reply = client.Receive(Encoding.UTF8);The UTF-8 message is received as "≻潃瑮湥≴›..." etc.
I tried to use UTF-16 and the message comes through OK, but the first symbols are still the little-endian \xFF \xFE BOM so when I try to feed it to the deserializer,
PythonMessage replyMessage = JsonConvert.DeserializeObject<PythonMessage>(reply); //PythonMessage is just a very simple class with properties, //not relevant to the problemI get an error (obviously occurring at the first symbol, \xFF):
Unexpected character encountered while parsing value: .Something is obviously wrong in the way I'm using encoding. Can you please show me the right way to do this?
最满意答案
UTF-16中必须使用字节顺序标记。 您可以使用UTF-16LE或UTF-16BE来假设特定的字节顺序,并且不会生成BOM。 也就是说,使用:
message_blob = simplejson.dumps(message).encode(encoding = "UTF-16le")The byte-order-mark is obligatory in UTF-16. You can use UTF-16LE or UTF-16BE to assume a particular byte order and the BOM will not be generated. That is, use:
message_blob = simplejson.dumps(message).encode(encoding = "UTF-16le")更多推荐
发布评论