0

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.

dbc
  • 104,963
  • 20
  • 228
  • 340
Sami Rajala
  • 191
  • 1
  • 11

2 Answers2

0

Can you try wrapping the call to JsonHelper.Deserialize... in a try catch and checking the innerexception to see if there is more detail. Additionally, you might try setting the accessor of your JsonObject class to public and see if that helps.

mreyeros
  • 4,359
  • 20
  • 24
  • Thanks for the response. Setting the accessor has no effect, just missed it out when I constructed a simple repro from the actual soluton. And the exception, it's caught somewhere inside the DataContractJsonSerializer and I can't get a hold on to it. – Sami Rajala Sep 26 '13 at 05:14
0

Started using json.NET which doesn't have any issues handling these kinds of responses.

Sami Rajala
  • 191
  • 1
  • 11