Which encoding should I specify for the serialized

2020-04-21 08:30发布

Suppose that I have a TextBox in my WinForms application.

When user clicks a button, the application should send a serialized value stored in this TextBox via TCP.

For the serialization I'm using Newtonsoft.Json library like this:

string json = JsonConvert.SerializeObject(credentials);

Where credentials is the object of class that holds TextBox's value.

Then I need to send it over network via TcpClient class:

TcpClient client = new TcpClient(IpAddress, Port);
NetworkStream stream = client.GetStream();
// ???

but I need to convert the json string to the byte array first, so I have to specify a text encoding. Which text encoding should I specify to be pretty safe?

I can't just set it to ASCII because user can enter unicode characters.

2条回答
祖国的老花朵
2楼-- · 2020-04-21 09:12

The .NET Framework uses the UTF-16 encoding (represented by the UnicodeEncoding class) to represent characters and strings. So you can use System.Text.Encoding.Unicode.GetBytes to get bytes of string.

For more information:

查看更多
一夜七次
3楼-- · 2020-04-21 09:12

Any Unicode encoding (UTF-7, UTF-8, UTF-16, UTF-32, …) can be used to encode Unicode characters. UTF-8 is possibly the most compact, depending on the writing systems used on your text.

查看更多
登录 后发表回答