3

我正在尝试使用 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: .

我使用编码的方式显然有问题。你能告诉我正确的方法吗?

4

1 回答 1

1

字节顺序标记在 UTF-16 中是强制性的。您可以使用 UTF-16LE 或 UTF-16BE 来假设特定的字节顺序,并且不会生成 BOM。也就是说,使用:

message_blob = simplejson.dumps(message).encode(encoding = "UTF-16le")
于 2013-10-11T07:02:11.377 回答