Click here to Skip to main content
15,890,557 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.4K   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 
I had a problem of being unable to cast an JsonArray object to JsonObject, I got rid of it by removing the '[' and ']' symbols in line 9. Otherwise, I'm not sure what's the probletm. You'll probably have to look deeper into the library and differences between JsonPrimitive, JsonObject, and JsonArray. I didn't spend enought time on that.
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 
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.