json.netasp.net-core.net-corec#-4.0

How do I convert a querystring to a json string in dotnet core?


how can I convert a query string to a JSON string of keys and values? For example, I want to convert

"ID=123&FNAME=test&LNAME=xyz"

to

{"ID":"123","FNAME":"test","LNAME":"xys"}

Solution

  • If you are using asp.net core, I suggest you could use System.Text.Json.JsonSerializer class to achieve your requirement.

    More details, you could refer to below codes:

            var dict = HttpUtility.ParseQueryString("ID=123&FNAME=test&LNAME=xyz");
            var json = System.Text.Json.JsonSerializer.Serialize(
                                dict.AllKeys.ToDictionary(k => k, k => dict[k])
                       );
    

    Result:

    enter image description here