Calling "Execute<T>.." method results in "Object reference not set to an instance of an object."

3,455 views
Skip to first unread message

Lee Duhl

unread,
Mar 30, 2012, 12:17:00 PM3/30/12
to rest...@googlegroups.com
I'm just getting into REST(full) development so I appologize if this is a newb question.
 
Working with VS 2010 Pro and version 102 of RestSharp.
 
As stated in the subject I'm getting a "Object reference not set to an instance of an object" error included in my "response" object that gets returned from within my GetTasks() method (code below).
 
I am succesfully getting my XML resonse back back from my service, but it does not appear to be getting deserialized into objects (code below) and I believe I have my "ArrayOfTask" and "Task" objects setup correctly to exactly match the XML repsponse.
 
End result is my Response.data object is comming back as null.
 
Any assistnace on what might be the issue would be appreciated.
 
Below is my class that inclues my objects for the above XML doc.
public class TaskList
 {       
   public TaskList()
   { }
 
   public class ArrayOfTask
   {
       [XmlAttribute]
       public string xmlns { get; set; }
       [XmlAttribute("xmlns:1")]
       public string xmlns1 { get; set; }
       public List<Task> Tasks { get; set; }
   }
 
   public class Task
   {
       public DateTime CompletedOn { get; set; }
       public DateTime CreatedOn { get; set; }
       public string Description { get; set; }
       public Int32 Id { get; set; }
       public string OwnerUserName { get; set; }
       public string Status { get; set; }
       public string Title { get; set; }
   }
 
   public ArrayOfTask GetTasks()
   {
       var client = new RestClient();
       client.BaseUrl = "http://localhost:8080/TeamTask";
       var request = new RestRequest();
       request.Resource = "{Tasks}";
       request.RootElement = "Task";
       request.AddParameter("Tasks", "Tasks", ParameterType.UrlSegment);
      
       var response = client.Execute<ArrayOfTask>(request);
 
       //Disregard the code below, it's only here to allow the class to compile while I work out the issues.
       ArrayOfTask myList = new ArrayOfTask();
       return myList;      
   }  
 }
 
Below is the XML response that I'm getting from my REST test service
<ArrayOfTask xmlns=\"http://schemas.datacontract.org/2004/07/TeamTask.Model\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">
     <Task>
          <CompletedOn>2009-03-15T00:00:00</CompletedOn>
          <CreatedOn>2009-12-01T00:00:00</CreatedOn>
          <Description>Write spec for new product</Description>
          <Id>1</Id>
          <OwnerUserName>user3</OwnerUserName>
          <Status>Completed</Status>
          <Title>Write Spec</Title>
     </Task>
     <Task>
          <CompletedOn i:nil=\"true\"/>
          <CreatedOn>2009-06-12T00:00:00</CreatedOn>
          <Description>Plan the company picnic</Description>
          <Id>6</Id>
          <OwnerUserName>user3</OwnerUserName>
          <Status>InProgress</Status>
          <Title>Plan Picnic</Title>
     </Task>
</ArrayOfTask>
 
Below is the expanded Response debugging watch point at the point after the "Execute<T>" method returns:
response  {RestSharp.RestResponse<TeamTask.Client.Model.TaskList.ArrayOfTask>} RestSharp.RestResponse<TeamTask.Client.Model.TaskList.ArrayOfTask>
 base    {RestSharp.RestResponse<TeamTask.Client.Model.TaskList.ArrayOfTask>} RestSharp.RestResponseBase {RestSharp.RestResponse<TeamTask.Client.Model.TaskList.ArrayOfTask>}
  Content  "<ArrayOfTask xmlns=\"http://schemas.datacontract.org/2004/07/TeamTask.Model\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"><Task><CompletedOn>2009-03-15T00:00:00</CompletedOn><CreatedOn>2009-12-01T00:00:00</CreatedOn><Description>Write spec for new product</Description><Id>1</Id><OwnerUserName>user3</OwnerUserName><Status>Completed</Status><Title>Write Spec</Title></Task><Task><CompletedOn i:nil=\"true\"/><CreatedOn>2009-02-12T00:00:00</CreatedOn><Description>Design the web UI for new product</Description><Id>2</Id><OwnerUserName>user1</OwnerUserName><Status>InProgress</Status><Title>Design UI</Title></Task><Task><CompletedOn i:nil=\"true\"/><CreatedOn>2009-03-20T00:00:00</CreatedOn><Description>Get customer feedback on UI</Description><Id>3</Id><OwnerUserName>user4</OwnerUserName><Status>Blocked</Status><Title>Get Feedback</Title></Task><Task><CompletedOn i:nil=\"true\"/><CreatedOn>2009-05-10T00:00:00</CreatedOn><Description>Write tests for domain logic</Description><Id>4</Id><OwnerUserName>user2</OwnerUserName><Status>Created</Status><Title>Write Tests</Title></Task><Task><CompletedOn i:nil=\"true\"/><CreatedOn>2009-05-10T00:00:00</CreatedOn><Description>Write documentation for new product</Description><Id>5</Id><OwnerUserName i:nil=\"true\"/><Status>Created</Status><Title>Write Docs</Title></Task><Task><CompletedOn i:nil=\"true\"/><CreatedOn>2009-06-12T00:00:00</CreatedOn><Description>Plan the company picnic</Description><Id>6</Id><OwnerUserName>user3</OwnerUserName><Status>InProgress</Status><Title>Plan Picnic</Title></Task></ArrayOfTask>" string
  ContentEncoding     "" string
  ContentLength       1561 long
  ContentType         "text/xml; charset=utf-8" string
+  Cookies             Count = 0 System.Collections.Generic.IList<RestSharp.RestResponseCookie> {System.Collections.Generic.List<RestSharp.RestResponseCookie>}
+  ErrorException      {"Object reference not set to an instance of an object."} System.Exception {System.NullReferenceException}
  ErrorMessage        "Object reference not set to an instance of an object." string
+  Headers Count       7 System.Collections.Generic.IList<RestSharp.Parameter> {System.Collections.Generic.List<RestSharp.Parameter>}
+  RawBytes            {byte[1561]} byte[]
  Request             null RestSharp.IRestRequest
  ResponseStatus      Error RestSharp.ResponseStatus
+  ResponseUri         {http://localhost:8080/TeamTask/Tasks} System.Uri
  Server              "ASP.NET Development Server/10.0.0.0" string
  StatusCode          OK System.Net.HttpStatusCode
  StatusDescription   "OK" string
+  Non-Public members    
  Data                null TeamTask.Client.Model.TaskList.ArrayOfTask
 
Thanks
Lee

Andy Cutright

unread,
Mar 30, 2012, 1:42:32 PM3/30/12
to rest...@googlegroups.com
I don't know a lot about deserializing Xml but isn't your root object ArrayOfTasks? Not Task? 

On Fri, Mar 30, 2012 at 9:17 AM, Lee Duhl <lee...@comcast.net> wrote:
   public ArrayOfTask GetTasks()
   {
       var client = new RestClient();
       client.BaseUrl = "http://localhost:8080/TeamTask";
       var request = new RestRequest();
       request.Resource = "{Tasks}";
       request.RootElement = "Task";
       request.AddParameter("Tasks", "Tasks", ParameterType.UrlSegment);
      
       var response = client.Execute<ArrayOfTask>(request);
 
       //Disregard the code below, it's only here to allow the class to compile while I work out the issues.
       ArrayOfTask myList = new ArrayOfTask();
       return myList;      
   }  
 }
 
 
Thanks
Lee

Cheers,
Andy 

Lee Duhl

unread,
Mar 30, 2012, 2:45:50 PM3/30/12
to rest...@googlegroups.com
ydna, thanks for that catch.  I did fix that but it did not solve my problems.  I'm still having the same issues.
 
Lee.

Andy Cutright

unread,
Mar 30, 2012, 3:16:39 PM3/30/12
to rest...@googlegroups.com
Can you deserialize a less complex XML document? When working with JSON i've run into some issues with documents that don't map well to POCOs; JSON documents that have a lot of nested objects particularly where an object contains multiple types, e.g.: 

{ [ { "1":"2"}, {"3":"4"} ], {"5":"6"}]} 

In these cases I've just taken the content and used the JObject from Newtonsoft to parse the JSON myself. 

Also, I generally don't set request.Resource and request.RootElement when I've parameterized the Execute method with an object into which the response.Content should be deserialized. Parameterizing with a concrete type is generally enough. 

Again, I'm not much of an XML expert with RestSharp. Or RestSharp. Or C# ;) Give me some Ruby and HTML ;) I'm not intending to start a flame war ;) 

John Sheehan

unread,
Apr 3, 2012, 1:01:22 AM4/3/12
to rest...@googlegroups.com
Replace this:

request.Resource = "{Tasks}";
request.RootElement = "Task";
request.AddParameter("Tasks", "Tasks", ParameterType.UrlSegment);

With this:

request.Resource = "Tasks";

You don't need to specify root element when you're starting with the root element, only if you want to start a level below it.

Lee Duhl

unread,
Apr 3, 2012, 12:21:27 PM4/3/12
to rest...@googlegroups.com
Thanks for the info that's good to know.
 
I believe I did find the issue with my original problem and it was the response I'm getting back from my REST service included escape characters in the response XML. Example: <CompletedOn i:nil=\"true\"/>
 
Being as the returned XML includes these characters, the response is not "well formed" and as such the RestSharp deserializer does not process it.
 
Thanks
Lee

Dimitris Panokostas

unread,
Jul 30, 2016, 1:43:46 PM7/30/16
to RestSharp
Lee, how did you overcome this issue? Did you use another Deserializer instead?

Sorry to dig up this old thread, but I just started trying out RestSharp and I seem to have come across a similar (or the same) problem. I'm trying a GET request to a Subsonic API server, and although I get the Content back correctly, the Data field in my response is null - and I get an "Object reference not set to instance of an object" exception.

I'm using VS2015, C# and RestSharp from Nuget (v105.2.3)

Here are the details, in case anyone wants to help:

My Execute method:

public static T Execute<T>(RestRequest request) where T : new()
        {
            var client = new RestClient {BaseUrl = new Uri(_serverName + "rest/")};
            request.AddParameter("u", Username);
            var salt = NewSalt();
            var token = Md5(Password + salt);
            request.AddParameter("t", token);
            request.AddParameter("s", salt);
            request.AddParameter("v", ApiVersion);
            request.AddParameter("c", "MusicBee");
            var response = client.Execute<T>(request);

            if (response.ErrorException != null)
            {
                const string message = "Error retrieving response from Subsonic server:";
                MessageBox.Show(message + "\n\n" + response.ErrorException, @"Subsonic Plugin Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            return response.Data;
        }


I used the "XSD" tool from Microsoft's .NET Tools package to create the classes directly from the API's .xsd file, so here's an extract on one class to give you an idea:

[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://subsonic.org/restapi")]
public partial class Playlists {
    
    private List<Playlist> playlistField;
    
    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("playlist")]
    public List<Playlist> playlist {
        get {
            return this.playlistField;
        }
        set {
            this.playlistField = value;
        }
    }
}


And here's the call to Execute which was supposed to get mapped to the "Playlists" class:

var request = new RestRequest
            {
                Resource = "getPlaylists.view",
                RootElement = "Playlists"
            };
            var result = Execute<Playlists>(request);

When this call executes, I get an exception containing the following:

System.NullReferenceException: Object reference not set to an instance of an object.
   at RestSharp.Deserializers.XmlDeserializer.GetElementByName(XElement root, XName name)
   at RestSharp.Deserializers.XmlDeserializer.Map(Object x, XElement root)
   at RestSharp.Deserializers.XmlDeserializer.Deserialize[T](IRestResponse response)
   at RestSharp.RestClient.Deserialize[T](IRestRequest request, IRestResponse raw)


meanwhile, in the response the Content is what I expected it to be (contains the correct information), although I noticed backslashes in the same way Lee mentions below:

"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<subsonic-response xmlns=\"http://subsonic.org/restapi\" status=\"ok\" version=\"1.14.0\">\r\n   <playlists>\r\n      
<playlist id=\"714\" name=\"1920s, 1930s, 1940s\" comment=\"Auto-imported from 1920s, 1930s, 1940s.pls\" owner=\"admin\" public=\"true\" songCount=\"107\" duration=\"23859\" created=\"2016-06-13T05:22:13.824Z\" changed=\"2016-07-29T22:09:08.677Z\" coverArt=\"pl-714\"/>\r\n

...


Should I try a custom deserializer, or does anyone see anything obviously wrong with my approach?
Reply all
Reply to author
Forward
0 new messages