diff --git a/src/Spoleto.Common/Helpers/HttpHelper.cs b/src/Spoleto.Common/Helpers/HttpHelper.cs index 3bef25b..d74ec89 100644 --- a/src/Spoleto.Common/Helpers/HttpHelper.cs +++ b/src/Spoleto.Common/Helpers/HttpHelper.cs @@ -18,7 +18,7 @@ namespace Spoleto.Common.Helpers public static class HttpHelper { /// - /// Converts the given object to HTTP query string. + /// Converts the given object to the HTTP query string. /// public static string ToQueryString(T body) { @@ -46,6 +46,39 @@ public static string ToQueryString(T body) return string.Join("&", args); } + /// + /// Converts the given object to the string . + /// + public static Dictionary ToStringDictionary(T body) + { + var bodyJson = JsonHelper.ToJson(body); + var dictionaryAsObjectValues = JsonHelper.FromJson>(bodyJson); + + var dictionary = new Dictionary(); + foreach (var key in dictionaryAsObjectValues.Keys) + { + var jsonValue = (JsonElement)dictionaryAsObjectValues[key]; + var objValue = FlattenJsonValue(jsonValue); + if (objValue is string str) + { + dictionary.Add(HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(str)); + } + else if (objValue is IEnumerable enumerable) + { + var count = 0; + foreach (string item in enumerable) + { + if (count++ > 0) + throw new ArgumentException("Cannot use IEnumerable argument with more than 1 element to convert to the Dictionary."); + + dictionary.Add(HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(item)); + } + } + } + + return dictionary; + } + private static object FlattenJsonValue(JsonElement objValue) { return objValue.ValueKind switch