public static Document ToDocument( this JToken jToken, MediaType mediaType, JsonSerializer serializer, IDocumentTypeResolver documentTypeResolver) { Document document; if (documentTypeResolver.TryGetTypeForMediaType(mediaType, out var documentType)) { try { if (mediaType.IsJson) { document = (Document)serializer.Deserialize(jToken.CreateReader(), documentType); } else if (jToken != null) { var parseFunc = TypeUtilEx.GetParseFuncForType(documentType); document = (Document)parseFunc(jToken.ToString()); } else { document = (Document)Activator.CreateInstance(documentType); } return(document); } catch (JsonException) { } catch (ArgumentException) { } catch (TypeLoadException) { // Ignore deserialization exceptions and return a Plain/Json document instead } } if (mediaType.IsJson) { if (jToken is IDictionary <string, JToken> contentJsonObject) { var contentDictionary = contentJsonObject.ToDictionary(k => k.Key, v => v.Value.GetTokenValue()); document = new JsonDocument(contentDictionary, mediaType); } else { throw new ArgumentException("The property is not a JSON"); } } else { document = new PlainDocument(jToken.ToString(), mediaType); } return(document); }
public static Document ToDocument(this JToken jToken, MediaType mediaType, global::Newtonsoft.Json.JsonSerializer serializer) { Type documentType; Document document; if (TypeUtil.TryGetTypeForMediaType(mediaType, out documentType)) { if (mediaType.IsJson) { document = (Document)serializer.Deserialize(jToken.CreateReader(), documentType); } else if (jToken != null) { var parseFunc = TypeUtilEx.GetParseFuncForType(documentType); document = (Document)parseFunc(jToken.ToString()); } else { document = (Document)Activator.CreateInstance(documentType); } } else { if (mediaType.IsJson) { var contentJsonObject = jToken as IDictionary <string, JToken>; if (contentJsonObject != null) { var contentDictionary = contentJsonObject.ToDictionary(k => k.Key, v => v.Value.GetTokenValue()); document = new JsonDocument(contentDictionary, mediaType); } else { throw new ArgumentException("The property is not a JSON"); } } else { document = new PlainDocument(jToken.ToString(), mediaType); } } return(document); }