Special characters in object making JSON invalid (DataContractJsonSerializer)

一世执手 提交于 2019-12-23 04:03:31

问题


I'm trying to serialize an object which has a special character in on of his strings (like ø or æ).

The problem is that when I use a special character like that, the last bit of my JSON is cut off?

Without special characters:

{"availability":"busy","name":"test","visibility":"public"}

With special characters:

{"availability":"busy","name":"tøst","visibility":"public"

I notice that for each special character, a character is cut off of my JSON string.

I use following code to serialize:

// 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();

回答1:


You need to use UTF-8 encoding. It will be something like this

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());

More info here



来源:https://stackoverflow.com/questions/20412442/special-characters-in-object-making-json-invalid-datacontractjsonserializer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!