using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; namespace RetailCrm.Extra { class Tools { public static string httpBuildQuery(Dictionary data) { if (data is Dictionary == false) { return String.Empty; } var parts = new List(); HandleItem(data, parts); return String.Join("&", parts); } private static void HandleItem(object data, List parts, string prefix = "") { if (data == null) return; if (data is Dictionary) { parts.Add(FormatDictionary((Dictionary)data, prefix)); } else { parts.Add(String.IsNullOrEmpty(data.ToString()) ? String.Empty : String.Format("{0}={1}", prefix, data.ToString())); } } private static string FormatDictionary(Dictionary obj, string prefix = "") { var parts = new List(); foreach (KeyValuePair kvp in obj) { string newPrefix = string.IsNullOrEmpty(prefix) ? String.Format("{0}{1}", prefix, kvp.Key) : String.Format("{0}[{1}]", prefix, kvp.Key); HandleItem(kvp.Value, parts, newPrefix); } return String.Join("&", parts); } public static Dictionary jsonDecode(string json) { return jsonObjectToDictionary((Dictionary)JsonConvert.DeserializeObject>(json)); } private static Dictionary jsonObjectToDictionary(Dictionary data) { Dictionary result = new Dictionary(); foreach (KeyValuePair kvp in data) { object valueObj = kvp.Value; string value = String.Empty; value = valueObj.ToString(); if (value != "") { if (valueObj.GetType() == typeof(JObject)) { valueObj = jsonObjectToDictionary((Dictionary)JsonConvert.DeserializeObject>(value)); result.Add(kvp.Key.ToString(), valueObj); } else if (valueObj.GetType() == typeof(JArray)) { var items = new List(); dynamic dynamicObject = JsonConvert.DeserializeObject(value); Dictionary newObject = new Dictionary(); int j = 0; foreach (var item in dynamicObject) { newObject.Add(j.ToString(), jsonObjectToDictionary(item.ToObject>())); j++; } result.Add(kvp.Key.ToString(), newObject); } else { result.Add(kvp.Key.ToString(), valueObj); } } } return result; } } }