2

I am having trouble using the 'Paste XML as Classes' feature in VS2012 to properly deserialize XML results from a Rest call using Web API.

The XML response from the call looks like this:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<SCResponse>
    <AccountId>86</AccountId>
    <Administrator>false</Administrator>
    <Email>6z@z.com</Email>
    <FirstName>6z@z.com</FirstName>
    <Label>false</Label>
    <LastName>6z@z.com</LastName>
    <link href="https://cnn.com" rel="news" title="News"/>
</SCResponse>

I copied this XML and used the handy new feature to paste this XML as classes:

namespace Models.account.response
{
    [XmlRoot(ElementName = "SCResponse")] // I added this so I could name the object Account
    [DataContract(Name = "SCResponse", Namespace = "")] // I added this as the namespace was causing me problems
    public partial class Account
    {
        public byte AccountId { get; set; }

        public bool Administrator { get; set; }

        public string Email { get; set; }

        public string FirstName { get; set; }

        public bool Label { get; set; }

        public string LastName { get; set; }

        [XmlElement("link")]
        public SCResponseLink[] Link { get; set; }
    }

    [XmlType(AnonymousType = true)]
    public partial class SCResponseLink
    {
        private string hrefField;

        private string relField;

        private string titleField;

        [XmlAttribute)]
        public string href { get; set; }

        XmlAttribute]
        public string rel { get; set; }

        [XmlAttribute]
        public string title { get; set; }
        }
    }
}

I call the REST endpoint like so:

string path = String.Format("account/{0}", id);
HttpResponseMessage response = client.GetAsync(path).Result;  // Blocking call!
if (response.IsSuccessStatusCode)
{
    // Parse the response body. Blocking!
    account = response.Content.ReadAsAsync<Models.account.response.Account>().Result;
}

and examine the fields of the Account object -- all are null or defaulting to initialized values.

In my Global.asax.cs Application_Start method, I am registering the XML Serializer:

GlobalConfiguration.Configuration.Formatters.XmlFormatter.UseXmlSerializer = true;
abatishchev
  • 98,240
  • 88
  • 296
  • 433
user486480
  • 183
  • 3
  • 12

1 Answers1

0

A simpler way to handle this might be to use the RestSharp library, which will do all of the deserialization for you. This will simplify your calls, and you won't need the XML attributes on your model.

Take a look here for a good example of doing aync calls with RestSharp:

How should I implement ExecuteAsync with RestSharp on Windows Phone 7?

Hopefully this helps.

Community
  • 1
  • 1
Garrett Vlieger
  • 9,354
  • 4
  • 32
  • 44