|
| 1 | +// Copyright (c) .NET Foundation and Contributors |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | +// |
| 15 | + |
| 16 | +using System.Collections.ObjectModel; |
| 17 | +using RestSharp.Extensions; |
| 18 | +using RestSharp.Serializers.Xml; |
| 19 | + |
| 20 | +namespace RestSharp.Serializers; |
| 21 | + |
| 22 | +public class RestSerializers { |
| 23 | + public IReadOnlyDictionary<DataFormat, SerializerRecord> Serializers { get; } |
| 24 | + |
| 25 | + public RestSerializers(Dictionary<DataFormat, SerializerRecord> records) |
| 26 | + => Serializers = new ReadOnlyDictionary<DataFormat, SerializerRecord>(records); |
| 27 | + |
| 28 | + public RestSerializers(SerializerConfig config) : this(config.Serializers) { } |
| 29 | + |
| 30 | + public IRestSerializer GetSerializer(DataFormat dataFormat) |
| 31 | + => Serializers.TryGetValue(dataFormat, out var value) |
| 32 | + ? value.GetSerializer() |
| 33 | + : throw new InvalidOperationException($"Unable to find a serializer for {dataFormat}"); |
| 34 | + |
| 35 | + internal RestResponse<T> Deserialize<T>(RestRequest request, RestResponse raw, ReadOnlyRestClientOptions options) { |
| 36 | + var response = RestResponse<T>.FromResponse(raw); |
| 37 | + |
| 38 | + try { |
| 39 | + request.OnBeforeDeserialization?.Invoke(raw); |
| 40 | + response.Data = DeserializeContent<T>(raw); |
| 41 | + } |
| 42 | + catch (Exception ex) { |
| 43 | + if (options.ThrowOnAnyError) throw; |
| 44 | + |
| 45 | + if (options.FailOnDeserializationError || options.ThrowOnDeserializationError) response.ResponseStatus = ResponseStatus.Error; |
| 46 | + |
| 47 | + response.AddException(ex); |
| 48 | + |
| 49 | + if (options.ThrowOnDeserializationError) throw new DeserializationException(response, ex); |
| 50 | + } |
| 51 | + |
| 52 | + return response; |
| 53 | + } |
| 54 | + |
| 55 | + /// <summary> |
| 56 | + /// Deserialize the response content into the specified type |
| 57 | + /// </summary> |
| 58 | + /// <param name="response">Response instance</param> |
| 59 | + /// <typeparam name="T">Deserialized model type</typeparam> |
| 60 | + /// <returns></returns> |
| 61 | + [PublicAPI] |
| 62 | + public T? DeserializeContent<T>(RestResponse response) { |
| 63 | + // Only attempt to deserialize if the request has not errored due |
| 64 | + // to a transport or framework exception. HTTP errors should attempt to |
| 65 | + // be deserialized |
| 66 | + if (response.Content == null) { |
| 67 | + return default; |
| 68 | + } |
| 69 | + |
| 70 | + // Only continue if there is a handler defined else there is no way to deserialize the data. |
| 71 | + // This can happen when a request returns for example a 404 page instead of the requested JSON/XML resource |
| 72 | + var deserializer = GetContentDeserializer(response); |
| 73 | + |
| 74 | + if (deserializer is IXmlDeserializer xml && response.Request is RestXmlRequest xmlRequest) { |
| 75 | + if (xmlRequest.XmlNamespace.IsNotEmpty()) xml.Namespace = xmlRequest.XmlNamespace!; |
| 76 | + |
| 77 | + if (xml is IWithDateFormat withDateFormat && xmlRequest.DateFormat.IsNotEmpty()) withDateFormat.DateFormat = xmlRequest.DateFormat!; |
| 78 | + } |
| 79 | + |
| 80 | + return deserializer != null ? deserializer.Deserialize<T>(response) : default; |
| 81 | + } |
| 82 | + |
| 83 | + IDeserializer? GetContentDeserializer(RestResponseBase response) { |
| 84 | + if (string.IsNullOrWhiteSpace(response.Content)) return null; |
| 85 | + |
| 86 | + var contentType = response.ContentType ?? DetectContentType()?.Value; |
| 87 | + if (contentType == null) return null; |
| 88 | + |
| 89 | + var serializer = Serializers.Values.FirstOrDefault(x => x.SupportsContentType(contentType)); |
| 90 | + |
| 91 | + var factory = serializer ?? |
| 92 | + (Serializers.ContainsKey(response.Request.RequestFormat) ? Serializers[response.Request.RequestFormat] : null); |
| 93 | + return factory?.GetSerializer().Deserializer; |
| 94 | + |
| 95 | + ContentType? DetectContentType() |
| 96 | + => response.Content[0] switch { |
| 97 | + '<' => ContentType.Xml, |
| 98 | + '{' or '[' => ContentType.Json, |
| 99 | + _ => null |
| 100 | + }; |
| 101 | + } |
| 102 | +} |
0 commit comments