Click here to Skip to main content
15,860,972 members
Articles / Programming Languages / PHP

Converting PHP arrays to a C# Dictionary

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
21 Dec 2011CPOL 30.2K   4   5
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: 

     

<p>
<code>

C#
  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;
        } 




License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Writer
Unknown
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionUnable to cast object of type 'Newtonsoft.Json.Linq.JObject' to type 'Newtonsoft.json.linq.jarray' Pin
real-insanity24-Dec-11 11:24
real-insanity24-Dec-11 11:24 
AnswerRe: Unable to cast object of type 'Newtonsoft.Json.Linq.JObject' to type 'Newtonsoft.json.linq.jarray' Pin
taralex3-Jan-12 2:31
taralex3-Jan-12 2:31 
GeneralRe: Unable to cast object of type 'Newtonsoft.Json.Linq.JObject' to type 'Newtonsoft.json.linq.jarray' Pin
real-insanity3-Jan-12 3:03
real-insanity3-Jan-12 3:03 
QuestionCould't you just use jsonencode? Pin
RedAnthrax_30-Nov-11 12:10
RedAnthrax_30-Nov-11 12:10 
Seems like you could just use the json_encode($myarray); in PHP and pass it as a string to Silverlight. Then you can decode it in Silverlight to an object.

http://stackoverflow.com/questions/4109807/parsing-json-data-with-c-sharp[^]
AnswerRe: Could't you just use jsonencode? Pin
taralex30-Nov-11 15:37
taralex30-Nov-11 15:37 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.