Sajith
Sajith

Reputation: 113

Query string of Webclient to json string - c#

I'm using below query for sending data to webAPI. It is working fine. How can I convert the query string that I used , into a json string within this function? Is it possible?

        WebClient wc = new WebClient();

        wc.Headers.Add("Authorization", "Bearer " + token);
        wc.QueryString.Add("unique_id", (checklist_ID.ToString()));
        wc.QueryString.Add("Question_no", (QNO.ToString()));
        wc.QueryString.Add("Question", t1_question.Text.ToString());
        wc.QueryString.Add("Password", t1_password.Text.ToString());

        var data = wc.UploadValues(url, "POST", wc.QueryString);

         //here I want this Querystring data in below json format 
         // [{"unique_id":"2233","Question_no":"43","Question":"XXXX??","Password":"testpswd"}]

        var responseString = UnicodeEncoding.UTF8.GetString(data);

Upvotes: 0

Views: 476

Answers (1)

Krishna Varma
Krishna Varma

Reputation: 4260

Use Linq and JsonConvert to get the desired result

//Use LINQ to convert the QueryString to Dictionary
var keyValuePairs = (
        from key in wc.QueryString.AllKeys
        from value in wc.QueryString.GetValues(key)
        select new { key, value }).ToDictionary(x => x.key, x => x.value);

//Use Newtonsoft.Json to Serialize the object to json format
Console.WriteLine(JsonConvert.SerializeObject(keyValuePairs));

Upvotes: 1

Related Questions