I am using RestSharp (version 104.4 via NuGet) to make calls to a Rest Web Service. I have designed a set of objects (POCO) which matches resources exposed
I came across this issue, and solved this a slightly different way than above, wanted to note it here.
We have a factory class that builds all of our requests. Looks like the following
public IRestRequest CreatePutRequest(string resource, TBody body)
{
var request = new RestRequest(resource)
{
Method = Method.PUT,
};
request.AddParameter("application/json", Serialize(body), ParameterType.RequestBody);
return request;
}
Rather than use the AddJsonBody and AddBody methods against the request, both of which cause serialisation, I used AddParameter which will add the object you pass in without serialisation. I created a method called Serialise, which uses JSON.net to serialise our class.
private object Serialize(T item)
{
return JsonConvert.SerializeObject(item);
}
This then allows us to use JSON.net's JsonProperty annotation above your propertys. Here is an example -
public class Example
{
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
[JsonProperty(PropertyName = "created")]
public DateTime Created { get; set; }
[JsonProperty(PropertyName = "updated")]
public DateTime Updated { get; set; }
}
- 热议问题