Пример #1
0
        /// <summary>
        /// Deserialize the JSON string into a proper object.
        /// </summary>
        /// <param name="response">The HTTP response.</param>
        /// <param name="type">Object type.</param>
        /// <returns>Object representation of the JSON string.</returns>
        public object Deserialize(IRestResponse response, Type type)
        {
            IList <Parameter> headers = response.Headers;

            if (type == typeof(byte[])) // return byte array
            {
                return(response.RawBytes);
            }

            if (type == typeof(Stream))
            {
                if (headers != null)
                {
                    var filePath = String.IsNullOrEmpty(Configuration.TempFolderPath)
                        ? Path.GetTempPath()
                        : Configuration.TempFolderPath;
                    var regex = new Regex(@"Content-Disposition=.*filename=['""]?([^'""\s]+)['""]?$");
                    foreach (var header in headers)
                    {
                        var match = regex.Match(header.ToString());
                        if (match.Success)
                        {
                            string fileName = filePath + SanitizeFilename(match.Groups[1].Value.Replace("\"", "").Replace("'", ""));
                            File.WriteAllBytes(fileName, response.RawBytes);
                            return(new FileStream(fileName, FileMode.Open));
                        }
                    }
                }
                var stream = new MemoryStream(response.RawBytes);
                return(stream);
            }

            if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object
            {
                return(DateTime.Parse(response.Content, null, System.Globalization.DateTimeStyles.RoundtripKind));
            }

            if (type == typeof(String) || type.Name.StartsWith("System.Nullable")) // return primitive type
            {
                return(ConvertType(response.Content, type));
            }

            // at this point, it must be a model (json)
            try
            {
                return(_responseSerializer.Deserialize(response.Content, type));
            }
            catch (Exception e)
            {
                throw new ApiException(500, e.Message);
            }
        }