Question

I'm trying out RestSharp for a WP7 project. Having some trouble deserializing some XML with RestSharp. The object is null. Here's some of the relevant XML:

<?xml version="1.0" encoding="utf-8"?>
<api_response xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <response_data>
        <employee_information>
          <employee>
            <employee_sf_name>David</employee_sf_name>
            <employee_first_name>Dave</employee_first_name>
            <employee_last_name>Jones</employee_last_name>
          </employee>
        </employee_information>
    </response_data>
</api_response>

And here's my request:

public static void executeRequest(Action<string> callback, string method)
    {
        var client = new RestClient();
        var request = new RestRequest(Method.POST);
        client.BaseUrl = App.url + method;
        request.AddParameter("secret_key", Application.secret_key);
        request.AddParameter("email", Application.email);
        request.AddParameter("password", Application.password);

        client.ExecuteAsync<Employee>(request, response =>
        {
            callback(response.Content); //prints the response as output
            Debug.WriteLine("firstname " + response.Data.employee_first_name);
        });
    }

And here's the Employee object:

public class Employee
{
    public Employee() { }
    public int employee_id { get; set; }
    public String employee_first_name { get; set; }
    public String employee_last_name { get;  set; }

}

Since the response comes back fine I tried deserializing it in a separate function, but without success:

public static void parse(string data)
    {
        Debug.WriteLine(data);
        XmlDeserializer xml = new XmlDeserializer();
        Employee employee = new Employee();
        employee = xml.Deserialize<Employee>(new RestResponse() { Content = data });

        Debug.WriteLine("last name " + employee.employee_last_name);
        Debug.WriteLine("firstname " + employee.employee_first_name);   

    }

Thanks in advance if anyone can shed some light on the issue.

Was it helpful?

Solution

First off, the closing tag needs to be a closing tag. After I fixed that, I set up an enclosing class:

public class employee_information
{
    public Employee employee { get; set; }
}

Then kept your original Employee class:

public class Employee
{
    public Employee() { }
    public int employee_id { get; set; }
    public String employee_first_name { get; set; }
    public String employee_last_name { get; set; }

}

Then, to deserialize it:

var empInfo = xml.Deserialize<employee_information>((new RestResponse() {Content = data}));

OTHER TIPS

Adding request.RootElement = "employee"; should work with your existing code. If you don't want to start that far down the tree, you need to create classes that match the entire hierarchy.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top