Tuesday, January 23, 2018

[Solved] Convert complex C#/JSON object to query string, ASPNET Core 2.0

I had to call an internal web page using HttpClient to get the HTML.  The Razor Page's OnGetAsync expected a C# complex object (nested types) as a parameter.  Here is a string extension, JsonAsQueryString, to convert a complex object into a query string for ASPNET Core 2.0.  I just converted the C# complex object to JSON using JsonConvert.Serialize, then use this extension method.

    public static class StringExtensions
    {
        public static string JsonAsQueryString(this string json)
        {
            return ParseJObject(json, string.Empty);
        }

        private static string ParseJObject(string json, string parentField = "")
        {
            var jo = (JObject)JsonConvert.DeserializeObject(json);
            var query = String.Join("&",
                jo.Children().Cast<JProperty>()
                .Select(jp => StringExtensions.ParseJProperty(jp, parentField)));

            return query;
        }

        private static string ParseJProperty(JProperty jp, string parentField)
        {
            var parentFormat = string.IsNullOrWhiteSpace(parentField) ? string.Empty : $"{parentField}.";

            if (jp.Value as JArray != null)
            {
                // this object is an array; repeat names
                var tokens = string.Join("&", jp.Value
                    .Select(t => $"{parentFormat}{jp.Name}={HttpUtility.UrlEncode(t.ToString())}"));

                return tokens;
            }
            else if (jp.Value.Type == JTokenType.Object)
            {
                // nested object; make a recursive call
                return StringExtensions.ParseJObject(jp.Value.ToString(), $"{parentFormat}{jp.Name}");
            }
            else
            {
                // normal member
                return $"{parentFormat}{jp.Name}={HttpUtility.UrlEncode(jp.Value.ToString())}";
            }
        }
    }

No comments:

Can't RDP? How to enable / disable virtual machine firewall for Azure VM

Oh no!  I accidentally blocked the RDP port on an Azure virtual machine which resulted in not being able to log into the VM anymore.  I did ...