我正在尝试序列化一个在其字符串上有特殊字符的对象(如ø或æ)。
问题是,当我使用这样的特殊字符时,我的JSON的最后一位被截断了吗?
没有特殊字符:
{"availability":"busy","name":"test","visibility":"public"}
使用特殊字符:
{"availability":"busy","name":"tøst","visibility":"public"
我注意到,对于每个特殊字符,都会从我的JSON字符串中删除一个字符。
我使用以下代码进行序列化:
// create new appointment
AppointmentClass appoint = new AppointmentClass();
appoint.name = subjectstring;
appoint.availability = "busy";
appoint.visibility = "public";
// generate json string from Appointment class
MemoryStream stream = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(AppointmentClass));
ser.WriteObject(stream, appoint);
stream.Position = 0;
StreamReader sr = new StreamReader(stream);
string payload = sr.ReadToEnd();
答案 0 :(得分:4)
您需要使用UTF-8编码。它会是这样的
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(AppointmentClass));
var ms = new MemoryStream();
serializer.WriteObject(ms, appoint);
//use utf encoding to accept special chars
var mytext = Encoding.UTF8.GetString(ms.ToArray());
更多信息here