diff --git a/src/Spoleto.Common/Helpers/JsonHelper.cs b/src/Spoleto.Common/Helpers/JsonHelper.cs index d8f7320..fae6ed1 100644 --- a/src/Spoleto.Common/Helpers/JsonHelper.cs +++ b/src/Spoleto.Common/Helpers/JsonHelper.cs @@ -1,10 +1,14 @@ using System; +using System.Collections; +using System.Collections.Generic; using System.IO; +using System.Linq; using System.Text.Encodings.Web; using System.Text.Json; using System.Text.Json.Serialization; using System.Text.Unicode; using System.Threading.Tasks; +using System.Web; namespace Spoleto.Common.Helpers { @@ -99,5 +103,44 @@ public static async Task FromJsonStreamAsync(Stream jsonStream) return body; } + + /// + /// Converts to a query string. + /// + public static string ToQueryString(T body) + { + var bodyJson = ToJson(body); + var dictionaryAsObjectValues = FromJson>(bodyJson); + + var args = new List(); + foreach (var key in dictionaryAsObjectValues.Keys) + { + var jsonValue = (JsonElement)dictionaryAsObjectValues[key]; + var objValue = FlattenJsonValue(jsonValue); + if (objValue is string str) + { + args.Add($"{HttpUtility.UrlEncode(key)}={HttpUtility.UrlEncode(str)}"); + } + else if (objValue is IEnumerable enumerable) + { + foreach (string item in enumerable) + { + args.Add($"{HttpUtility.UrlEncode(key)}={HttpUtility.UrlEncode(item)}"); + } + } + } + + return string.Join("&", args); + } + + private static object FlattenJsonValue(JsonElement objValue) + { + return objValue.ValueKind switch + { + JsonValueKind.String => objValue.GetString(), + JsonValueKind.Array => objValue.EnumerateArray().Select(FlattenJsonValue), + _ => objValue.GetRawText() + }; + } } }