Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to serialize a json string to a form post data

Tags:

c#

json.net

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?

like image 721
WriteEatSleepRepeat Avatar asked Nov 19 '13 14:11

WriteEatSleepRepeat


People also ask

How pass data from JSON to form?

Using the JSON. stringify() method then format the plain form data as JSON. Specify the HTTP request method as POST and using the header field of the Fetch API specify that you are sending a JSON body request and accepting JSON responses back. Then set the request body as JSON created from the form fields.

How do you store data from HTML form to JSON?

var formData = JSON. stringify($("#emails_form"). serializeArray()); If you want to store formData in a JSON file, you need to post it to the server (e.g. per AJAX) and save it.

What is serialization in JSON?

JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object).


2 Answers

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();
like image 113
Brian Rogers Avatar answered Oct 10 '22 17:10

Brian Rogers


You don't post JSON like that. You set the Content-Type header to "application/json" and then you simply fill the content body with the JSON as-is.

There is no built in support in C# or JSON.NET to serialize JSON into form post data, but you can probably use LINQ to JSON to write a translater yourself relatively easy, assuming the JSON format is simple enough.

like image 44
Tobberoth Avatar answered Oct 10 '22 18:10

Tobberoth