使用DataContractJsonSerializer发序列化对象时出现的异常

最近服务器上的某个程序的错误日志中频繁出现以下异常:

Deserialising: There was an error deserializing the object of type {type}.

The token '"' was expected but found 'Â'

通过分析发现是使用DataContractJsonSerializer发序列化对象时出现的异常

但是把日志中出错的json串拷贝到本机测试时又没有问题,很是费解,最后在网上找到了解决办法

http://stackoverflow.com/questions/23909231/datacontractjsonserializer-readobject-sometimes-throws-the-token-was-expected

我的反序列化的代码如下:

            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            MemoryStream ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(json.ToCharArray()));
            T obj = (T)serializer.ReadObject(ms);
            ms.Close();

错误原因是因为json串种含有大量非ANSI的字符,解决办法如下:

            byte[] result = Encoding.UTF8.GetBytes(json);
            using (var jsonReader = JsonReaderWriterFactory.CreateJsonReader(result, XmlDictionaryReaderQuotas.Max))
            {
                var serializer = new DataContractJsonSerializer(typeof(T));
                T obj = (T)serializer.ReadObject(jsonReader);
                return obj;
            }

通过测试,异常解决。

原文地址:https://www.cnblogs.com/DCLi/p/5198227.html