C# hashtable 转json

来源:互联网 发布:pp助手mac版铃声 编辑:程序博客网 时间:2024/06/05 20:41

以前常常码php, 换成C#就习惯用hashtable当数php数组代替,而生成json不想用json.net dll 只能自个写了,


hashtable hr=new hashtable();

      hr.add("name","pan");

      hr.add("die","True");

      hashtable log=new hashtable();

           log.add("1","sdfsdfsdf");

           log.add("2","delete user");

     hr.add("log",log);

     



public static string HashtableToJson(Hashtable hr,int readcount=0)

        {
            string json="{";  
            foreach(DictionaryEntry row in hr)
            {
                try
                {
                    string key = "\"" + row.Key + "\":"; 
                    if (row.Value is Hashtable)
                    {
                        Hashtable t = (Hashtable)row.Value;
                        if(t.Count>0)
                        {
                            json += key + HashtableToJson(t, readcount++)+",";
                        }
                        else { json += key + "{},"; }
                    }
                    else
                    { 
                        string value = "\"" + row.Value.ToString() + "\",";
                        json += key   + value;
                    }
                }
                catch { }

            } 

            

          //  json = MyString.ClearEndChar(json);  


            json = json + "}"; 
            return json;
        }
0 0