I'm seeing XmlException occuring from the output whenever the JSON being deserialized contains characters like '@'. 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.
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
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.