获取用于反序列化响应的RestSharp反序列化器

时间:2016-11-11 11:05:04

标签: c# .net serialization restsharp

使用ressharp打电话时

response = client.Execute<SomeClass>(request);

我需要知道里面使用哪个反序列化器restsharp来反序列化这个响应。 我知道restsharp会根据服务器返回的内容类型确定反序列化器。

我需要这样的东西

var deserializator = responce.GetUsedDeserializator();

甚至

var deserializator = restclient.GetDeserializatorForContentType(responce.ContentType)

1 个答案:

答案 0 :(得分:0)

这是一种简单的方法。我找到的唯一方法是提取restsharp源代码。

public static class RestSharpExtensions
{
    private static readonly Regex structuredSyntaxSuffixRegex = new Regex("\\+\\w+$", RegexOptions.Compiled);

    private static Dictionary<string, IDeserializer> contentTypeToDeserializerMap = new Dictionary
        <string, IDeserializer>
    {
        {"application/json", new JsonDeserializer()},
        {"application/xml", new XmlDeserializer()},
        {"text/json", new JsonDeserializer()},
        {"text/x-json", new JsonDeserializer()},
        {"text/javascript", new JsonDeserializer()},
        {"text/xml", new XmlDeserializer()},
        {"*+json",  new JsonDeserializer()},
        {"*+xml", new XmlDeserializer()},
        {"*",  new XmlDeserializer()}
    };


    public static IDeserializer GetDeserializer(this IRestResponse restResponse)
    {
        var contentType = restResponse.ContentType;
        if (contentType == null)
            throw new ArgumentNullException("contentType");
        if (string.IsNullOrEmpty(contentType) && contentTypeToDeserializerMap.ContainsKey("*"))
            return contentTypeToDeserializerMap["*"];
        int length = contentType.IndexOf(';');
        if (length > -1)
            contentType = contentType.Substring(0, length);
        if (contentTypeToDeserializerMap.ContainsKey(contentType))
            return contentTypeToDeserializerMap[contentType];
        Match match = structuredSyntaxSuffixRegex.Match(contentType);
        if (match.Success)
        {
            string key = "*" + match.Value;
            if (contentTypeToDeserializerMap.ContainsKey(key))
                return contentTypeToDeserializerMap[key];
        }
        if (contentTypeToDeserializerMap.ContainsKey("*"))
            return contentTypeToDeserializerMap["*"];
        return (IDeserializer)null;
    }

}