Skip to content

Commit

Permalink
ToQueryString
Browse files Browse the repository at this point in the history
  • Loading branch information
o.nadymov committed Mar 21, 2024
1 parent cba6229 commit a440cfa
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions src/Spoleto.Common/Helpers/JsonHelper.cs
Original file line number Diff line number Diff line change
@@ -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
{
Expand Down Expand Up @@ -99,5 +103,44 @@ public static async Task<T> FromJsonStreamAsync<T>(Stream jsonStream)

return body;
}

/// <summary>
/// Converts to a query string.
/// </summary>
public static string ToQueryString<T>(T body)
{
var bodyJson = ToJson(body);
var dictionaryAsObjectValues = FromJson<Dictionary<string, object>>(bodyJson);

var args = new List<string>();
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()
};
}
}
}

0 comments on commit a440cfa

Please sign in to comment.