0

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);
4
  • 1
    sending JSON on the querystring of the URL doesn't make much sense. Either send querystring values separately or send JSON in the body of the request. (Or you can in fact send url-encoded values (i.e. they look like a querystring) in the body of the request, too.). See stackoverflow.com/questions/36723705/… if you want to know how to set the content of the request body using WebClient.
    – ADyson
    Commented Feb 6, 2020 at 15:09
  • this is for log the data in a text file that I send to webapi
    – Sajith
    Commented Feb 6, 2020 at 15:18
  • Ok. And your point is? How does that relate to what you've asked, or what I've just told you?
    – ADyson
    Commented Feb 6, 2020 at 15:20
  • I'm trying to get this array [{"unique_id":"2233","Question_no":"43","Question":"XXXX??"}] from QueryString I used to send.
    – Sajith
    Commented Feb 6, 2020 at 15:21

1 Answer 1

1

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));
2
  • is there any way to hide the password key as "*****" in this keyValuePairs? for ex: [{"unique_id":"2233","Question_no":"43","Question":"XXXX??","Password":"******"}]
    – Sajith
    Commented Feb 6, 2020 at 19:07
  • keyValuePairs.FirstOrDefault (kvp=>kvp.Key.Equals ("Password"))?.Value = "******" Commented Feb 6, 2020 at 19:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.