0

Answers such as this seem to go through several steps getting a string for the JSON content returned by an HTTP web request, which is then passed into JSON.net for deserialization.

Is there any shortcut that can be used e.g. do any API methods accept WebResponse or other intermediary objects? I couldn't see any but if they exist it would make for slightly neater code.

Community
  • 1
  • 1
Mr. Boy
  • 60,845
  • 93
  • 320
  • 589

1 Answers1

0

No, it does not. JSON.net doesn't mingle with HTTP directly. You have to do manual deserialization.

However, for the sake of neatness, might I suggest RestSharp? It makes my own code look a lot neater. You can implement ISerializer and inside of that, have your serialize method internally utilise all of Newtonsoft. RestClient handles all of the heavy lifting in regards to the WebResponse and will automatically deserialize for you. And no, it's not my library.

public class Employee
{
   [JsonProperty(PropertyName = "employee_name")]
   public string Name { get; set; }
}

private IRestResponse<Employee> GetEmployee()
{
   var request = new RestRequest();
   request.Resource = "/api/employees"
   request.Method = Method.GET;
   var response = Execute<Employee>(request);
}

public IRestResponse<T> Execute<T>(RestRequest request) where T : new()
{
   // Pass in reusable ISerializer (can internally use Newtonsoft)
   request.JsonSerializer = new JsonNetSerializer(); 
   return client.Execute<T>(request); // Client is of type RestClient
}

Alternatively, you can do this and not implement a serializer at all, because it provides a Content property that you can pass into JSON.net as a string:

public IRestResponse<T> Execute<T>(RestRequest request) where T : new()
{
   var response = client.Execute(request); // Client is of type RestClient
   return JsonConvert.DeserializeObject<T>(response.Content);
}
Frozenthia
  • 759
  • 3
  • 9