I'm trying to do a very simple example of using RestSharp's Execute method of querying a rest endpoint and serializing to a POCO. However, everything I try results in a response.Data object that has all properties with a NULL value.
Here is the JSON response:
{
"Result":
{
"Location":
{
"BusinessUnit": "BTA",
"BusinessUnitName": "CASINO",
"LocationId": "4070",
"LocationCode": "ZBTA",
"LocationName": "Name of Casino"
}
}
}
Here is my test code
[TestMethod]
public void TestLocationsGetById()
{
//given
var request = new RestRequest();
request.Resource = serviceEndpoint + "/{singleItemTestId}";
request.Method = Method.GET;
request.AddHeader("accept", Configuration.JSONContentType);
request.RootElement = "Location";
request.AddParameter("singleItemTestId", singleItemTestId, ParameterType.UrlSegment);
request.RequestFormat = DataFormat.Json;
//when
Location location = api.Execute<Location>(request);
//then
Assert.IsNotNull(location.LocationId); //fails - all properties are returned null
}
And here is my API code
public T Execute<T>(RestRequest request) where T : new()
{
var client = new RestClient();
client.BaseUrl = Configuration.ESBRestBaseURL;
//request.OnBeforeDeserialization = resp => { resp.ContentLength = 761; };
var response = client.Execute<T>(request);
return response.Data;
}
And finally, here is my POCO
public class Location
{
public string BusinessUnit { get; set; }
public string BusinessUnitName { get; set; }
public string LocationId { get; set; }
public string LocationCode { get; set; }
public string LocationName { get; set; }
}
Additionally, the ErrorException and ErrorResponse properties on the response are NULL.
This seems like a very simple case, but I've been running around in circles all day! Thanks.
What is the Content-Type
in the response? If not a standard content type like "application/json", etc. then RestSharp won't understand which deserializer to use. If it is in fact a content type not "understood" by RestSharp (you can verify by inspecting the Accept
sent in the request), then you can solve this by doing:
client.AddHandler("my_custom_type", new JsonDeserializer());
EDIT:
Ok, sorry, looking at the JSON again, you need something like:
public class LocationResponse
public LocationResult Result { get; set; }
}
public class LocationResult {
public Location Location { get; set; }
}
And then do:
client.Execute<LocationResponse>(request);