Skip to main content
 首页 » 编程设计

c#之对象中的特殊字符使 JSON 无效(DataContractJsonSerializer)

2024年02月13日14grandyang

我正在尝试序列化一个对象,该对象在他的一个字符串中有一个特殊字符(如 ø 或 æ)。

问题是当我使用这样的特殊字符时,我的 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(); 

请您参考如下方法:

您需要使用 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