我有一个我使用的辅助方法:
private IRestRequest CreateRequest(Uri uri, Method method, object body)
{
IRestRequest request = new RestRequest(uri, method);
request.Resource = uri.ToString();
request.Timeout = _timeout;
if (body != null)
{
request.AddHeader("Content-Type", "application/json");
request.RequestFormat = DataFormat.Json;
request.JsonSerializer = new CustomConverter {ContentType = "application/json"};
request.AddBody(body);
}
return request;
}
转换器看起来像这样:
class CustomConverter : ISerializer, IDeserializer
{
private static readonly JsonSerializerSettings SerializerSettings;
static CustomConverter ()
{
SerializerSettings = new JsonSerializerSettings
{
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
Converters = new List<JsonConverter> { new IsoDateTimeConverter() },
NullValueHandling = NullValueHandling.Ignore
};
}
public string Serialize(object obj)
{
return JsonConvert.SerializeObject(obj, Formatting.None, SerializerSettings);
}
public T Deserialize<T>(IRestResponse response)
{
var type = typeof(T);
return (T)JsonConvert.DeserializeObject(response.Content, type, SerializerSettings);
}
string IDeserializer.RootElement { get; set; }
string IDeserializer.Namespace { get; set; }
string IDeserializer.DateFormat { get; set; }
string ISerializer.RootElement { get; set; }
string ISerializer.Namespace { get; set; }
string ISerializer.DateFormat { get; set; }
public string ContentType { get; set; }
}
然后我可以在返回的请求上调用 Execute。我想知道序列化是否需要由 RestSharp 框架完成(通过设置要使用的序列化程序)。