Iterating over JSON object in C#

后端 未结 3 1820
死守一世寂寞
死守一世寂寞 2020-11-28 05:05

I am using JSON.NET in C# to parse a response from the Klout API. My response is like this:

[
  {
    \"id\": \"5241585099662481339\",
    \"displayName\":          


        
3条回答
  •  遥遥无期
    2020-11-28 05:54

    This worked for me, converts to nested JSON to easy to read YAML

        string JSONDeserialized {get; set;}
        public int indentLevel;
    
        private bool JSONDictionarytoYAML(Dictionary dict)
        {
            bool bSuccess = false;
            indentLevel++;
    
            foreach (string strKey in dict.Keys)
            {
                string strOutput = "".PadLeft(indentLevel * 3) + strKey + ":";
                JSONDeserialized+="\r\n" + strOutput;
    
                object o = dict[strKey];
                if (o is Dictionary)
                {
                    JSONDictionarytoYAML((Dictionary)o);
                }
                else if (o is ArrayList)
                {
                    foreach (object oChild in ((ArrayList)o))
                    {
                        if (oChild is string)
                        {
                            strOutput = ((string)oChild);
                            JSONDeserialized += strOutput + ",";
                        }
                        else if (oChild is Dictionary)
                        {
                            JSONDictionarytoYAML((Dictionary)oChild);
                            JSONDeserialized += "\r\n";  
                        }
                    }
                }
                else
                {
                    strOutput = o.ToString();
                    JSONDeserialized += strOutput;
                }
            }
    
            indentLevel--;
    
            return bSuccess;
    
        }
    

    usage

            Dictionary JSONDic = new Dictionary();
            JavaScriptSerializer js = new JavaScriptSerializer();
    
              try {
    
                JSONDic = js.Deserialize>(inString);
                JSONDeserialized = "";
    
                indentLevel = 0;
                DisplayDictionary(JSONDic); 
    
                return JSONDeserialized;
    
            }
            catch (Exception)
            {
                return "Could not parse input JSON string";
            }
    

提交回复
热议问题