/// <summary> /// Apply a patch to an object to transform it to another type. /// </summary> /// <param name="patch">The patch</param> /// <param name="obj">The object</param> /// <param name="options">Serializer options.</param> /// <typeparam name="TOriginal">The type of the original object.</typeparam> /// <typeparam name="TTarget">The type of the target object.</typeparam> /// <returns>New instance of patched object</returns> /// <exception cref="InvalidOperationException">Thrown when the patch cannot be applied.</exception> public static TTarget Apply <TOriginal, TTarget>(this JsonPatch patch, TOriginal obj, JsonSerializerOptions?options = null) { using var doc = JsonDocument.Parse(JsonSerializer.Serialize(obj, options)); var patchResult = patch.Apply(doc.RootElement); if (!patchResult.IsSuccess) { throw new InvalidOperationException($"{patchResult.Error} Operation: {patchResult.Operation}"); } var result = JsonSerializer.Deserialize <TTarget>(patchResult.Result.GetRawText(), options); return(result); }
public async Task <HttpStatusCode> PatchAsync(int channelId, Json.Patch.JsonPatch patch) { using var client = _httpClientFactory.CreateClient(); client.BaseAddress = new Uri(_channel.MasterCommunication !.ToString()); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", await GetOrRefreshTokenAsync().ConfigureAwait(false)); //todo replace when System.Text.Json support jsonpatch using var content = new StringContent(JsonSerializer.Serialize(patch), Encoding.Default, "application/json-patch+json"); var postResponse = await client .PatchAsync(new Uri($"{client.BaseAddress}api/channel?id={channelId}"), content).ConfigureAwait(false); if (postResponse.IsSuccessStatusCode) { return(JsonSerializer.Deserialize <HttpStatusCode>(await postResponse.Content.ReadAsStringAsync().ConfigureAwait(false), new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }) !); } throw new HttpRequestException(postResponse.Headers.ToString()); }
/// <summary> /// Apply a patch to an object to transform its data. /// </summary> /// <param name="patch">The patch</param> /// <param name="obj">The object</param> /// <typeparam name="T">The type of the object.</typeparam> /// <returns>New instance of patched object</returns> /// <exception cref="InvalidOperationException">Thrown when the patch cannot be applied.</exception> public static T Apply <T>(this JsonPatch patch, T obj) { return(Apply <T, T>(patch, obj)); }