在对象使得JSON无效的特殊字符(DataContractJsonSerializer) [英] Special characters in object making JSON invalid (DataContractJsonSerializer)

查看:210
本文介绍了在对象使得JSON无效的特殊字符(DataContractJsonSerializer)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图序列化具有特殊字符在他的琴弦的对象(如直径或℃)。



的问题是,当我使用这样的特殊字符,我的JSON的最后一位被切断?



如果没有特殊字符:

  {可用性:忙,名:测试,知名度:公共} 

使用特殊字符:

  {可用性:忙,名:托斯特,可见性:公

我注意到,每一个特殊字符,一个字符被切断我的JSON字符串。



我使用下面的代码序列化:

  //创建新的约会
AppointmentClass任命=新AppointmentClass();
appoint.name = subjectstring;
appoint.availability =忙;
appoint.visibility =公开;

//生成预约类
MemoryStream的流JSON字符串=新的MemoryStream();
DataContractJsonSerializer SER =新DataContractJsonSerializer(typeof运算(AppointmentClass));
ser.WriteObject(流,委);
stream.Position = 0;
StreamReader的SR =新的StreamReader(流);
串有效载荷= sr.ReadToEnd();


解决方案

您需要使用UTF-8编码。这将是这样的。



  DataContractJsonSerializer SER =新DataContractJsonSerializer(typeof运算(AppointmentClass)); 
变种MS =新的MemoryStream();
serializer.WriteObject(MS,委);
//使用UTF编码,接受特殊字符
VAR MYTEXT = Encoding.UTF8.GetString(ms.ToArray());



更多信息的这里


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

解决方案

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

这篇关于在对象使得JSON无效的特殊字符(DataContractJsonSerializer)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆