65.9K
CodeProject is changing. Read more.
Home

Converting PHP arrays to a C# Dictionary

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Nov 30, 2011

CPOL
viewsIcon

31195

downloadIcon

103

PHP array to C# Dictionary conversion.

Removed the previous code, it was a totally bad idea and awful code.  Now I'm passing the Json array to Silverlight using json_encode() and using Newtonsoft.Json library with the following simple function: 

     

  public Dictionary<string, object> Parse(string array)
        { 
            Dictionary<string, object> result = new Dictionary<string, object>();
            Newtonsoft.Json.Linq.JObject obj = (Newtonsoft.Json.Linq.JObject)JsonConvert.DeserializeObject(array);
            foreach (KeyValuePair<string, Newtonsoft.Json.Linq.JToken> kvp in obj)
            {
                if (kvp.Value.ToString().Contains('{'))
                {
                    result.Add(kvp.Key, Parse(kvp.Value.ToString().Replace("[", "").Replace("]", "")));
                }
                else
                {
                    result.Add(kvp.Key, kvp.Value.ToString());
                }
            }
            return result;
        }