【问题标题】:Special characters in object making JSON invalid (DataContractJsonSerializer)对象中的特殊字符使 JSON 无效 (DataContractJsonSerializer)
【发布时间】:2013-12-05 22:51:20
【问题描述】:

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

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

【问题讨论】:

标签: c# json windows-phone character


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多