how to serialize a json string to a form post data
c#, json.net
Solution
This can be done by first deserializing your JSON to a `Dictionary<string, string>`, then iterating through the key-value pairs in the dictionary and building up a querystring from that.
However, keep in mind that querystring format (`application/x-www-form-urlencoded`) is not a hierarchical format, while JSON is. So your JSON object can only be a simple object with key-value pairs (no arrays or nested objects). If your JSON is more complicated than that, you will have to do some more work to flatten it before you can convert it to a querystring.
Demo:
class Program
{
static void Main(string[] args)
{
string json = @"
{
""key1"" : ""value1"",
""key2"" : ""value2"",
""int"" : 5,
""bool"" : true,
""decimal"" : 3.14,
""punct"" : ""x+y=z""
}";
var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
StringBuilder sb = new StringBuilder();
foreach (KeyValuePair<string, string> kvp in dict)
{
if (!string.IsNullOrEmpty(kvp.Key) && !string.IsNullOrEmpty(kvp.Value))
{
if (sb.Length > 0) sb.Append('&');
sb.Append(HttpUtility.UrlEncode(kvp.Key));
sb.Append('=');
sb.Append(HttpUtility.UrlEncode(kvp.Value));
}
}
var postDataString = sb.ToString();
Console.WriteLine(postDataString);
}
}
Output:
key1=value1&key2=value2&int=5&bool=True&decimal=3.14&punct=x%2by%3dz
As was mentioned in the comments, you can use the `FormUrlEncodedContent` class to do the same thing. Replace the `StringBuilder` and `foreach` loop in the code above with the following (but note this approach requires `async/await`):
var formUrlEncodedContent = new FormUrlEncodedContent(dict);
var postDataString = await formUrlEncodedContent.ReadAsStringAsync();
Problem
I need to POST a JSON string to a page. The page is external and out of my control, and it expects the post data to be in the web-form post format (`key1=value1&key2=value2`) How can I convert the JSON string to this format?