简体   繁体   English

特殊字符XmlException和DataContractJsonSerializer

[英]Special characters, XmlException and DataContractJsonSerializer

I'm seeing XmlException occuring from the output whenever the JSON being deserialized contains characters like '@'. 每当看到要反序列化的JSON包含诸如'@'之类的字符时,我就会在输出中看到XmlException。 In the end, it still successfully deserializes it, but it bugs me not knowing what's going wrong. 最后,它仍然可以成功地反序列化,但是令我感到困惑的是,我不知道出了什么问题。 It also slows down debugging a lot as many of the json responses contais these characters. 由于许多json响应包含了这些字符,因此它也减慢了调试速度。

Code to reproduce: 复制代码:

public static class JsonHelper
{     
    public static T Deserialize<T>(string json)
    {
        var obj = Activator.CreateInstance<T>();
        using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
        {
            var serializer = new DataContractJsonSerializer(obj.GetType());
            obj = (T)serializer.ReadObject(ms);
        }
        return obj;
    }
}

[DataContract]
class JsonObject
{
    [DataMember(Name = "@name")]
    public string Name { get; set; }
}


public partial class MainPage : PhoneApplicationPage
{
    private static string json = "{\"@name\":\"Something\"}";

    // Constructor
    public MainPage()
    {
        InitializeComponent();

        var obj = JsonHelper.Deserialize<JsonObject>(json);
        // obj.Name now contains "Something" as it should, but an XmlException has also happened.
    }

An exception of type 'System.Xml.XmlException' occurred in System.Xml.ni.dll and wasn't handled before a managed/native boundary System.Xml.ni.dll中发生了类型为'System.Xml.XmlException'的异常,在托管/本地边界之前未进行处理

Am I missing something? 我想念什么吗? I wouldn't want to do any search&replace before deserializing, if possible. 如果可能的话,我不想在反序列化之前进行任何搜索和替换。

Edit 编辑

If I run the same code in a .NET 4.5 console app, I don't see this exception happening. 如果在.NET 4.5控制台应用程序中运行相同的代码,则不会发生此异常。

Can you try wrapping the call to JsonHelper.Deserialize... in a try catch and checking the innerexception to see if there is more detail. 您可以尝试将对JsonHelper.Deserialize ...的调用包装在try catch中,并检查innerexception以查看是否有更多详细信息。 Additionally, you might try setting the accessor of your JsonObject class to public and see if that helps. 另外,您可以尝试将JsonObject类的访问器设置为public,看看是否有帮助。

开始使用json.NET ,它在处理此类响应方面没有任何问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM