Skip to content

Commit

Permalink
ToStringDictionary
Browse files Browse the repository at this point in the history
  • Loading branch information
o.nadymov committed Jun 5, 2024
1 parent 9f67073 commit dfd10ad
Showing 1 changed file with 34 additions and 1 deletion.
35 changes: 34 additions & 1 deletion src/Spoleto.Common/Helpers/HttpHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ namespace Spoleto.Common.Helpers
public static class HttpHelper
{
/// <summary>
/// Converts the given object to HTTP query string.
/// Converts the given object to the HTTP query string.
/// </summary>
public static string ToQueryString<T>(T body)
{
Expand Down Expand Up @@ -46,6 +46,39 @@ public static string ToQueryString<T>(T body)
return string.Join("&", args);
}

/// <summary>
/// Converts the given object to the string <see cref="Dictionary{String, String}"/>.
/// </summary>
public static Dictionary<string,string> ToStringDictionary<T>(T body)
{
var bodyJson = JsonHelper.ToJson(body);
var dictionaryAsObjectValues = JsonHelper.FromJson<Dictionary<string, object>>(bodyJson);

var dictionary = new Dictionary<string, string>();
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
Expand Down

0 comments on commit dfd10ad

Please sign in to comment.