问题
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