0

我正在为一个 WP7 项目尝试 RestSharp。使用 RestSharp 反序列化某些 XML 时遇到一些麻烦。对象为空。以下是一些相关的 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>

这是我的要求:

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);
        });
    }

这是 Employee 对象:

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; }

}

由于响应恢复正常,我尝试在单独的函数中对其进行反序列化,但没有成功:

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);   

    }

如果有人能对这个问题有所了解,请提前致谢。

4

2 回答 2

4

首先,结束标签必须是结束标签。在我修复它之后,我设置了一个封闭类:

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

然后保留您原来的 Employee 类:

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; }

}

然后,反序列化它:

var empInfo = xml.Deserialize<employee_information>((new RestResponse() {Content = data}));
于 2012-05-22T12:33:48.043 回答
1

添加request.RootElement = "employee";应该适用于您现有的代码。如果您不想从树的底部开始,则需要创建与整个层次结构匹配的类。

于 2012-05-22T17:54:12.477 回答