1. 程式人生 > >C# 產生JSON串

C# 產生JSON串

 

由於JSON是現在前後臺傳輸的標準,快速生產JSON串現在很是重要啊,

找了那麼久,找到一個還算簡單的。

 

 

        ///<summary>
        ///查詢省市區
        /// </summary>
        public string SearchArea()
        {
            string Data = HttpRuntime.Cache["AreaName"] as string;

            if (Data == null)
            {
                IList
<Mobile.Domain.Entities.Area> AreaList = AreaRepository.LoadByCondition("From Area", new string[] { }, new object[] { }); var AreaListFirst = AreaList.Where((name) => { return name.Parent_ID == 0; }); //所有省的集合 List<JObject> JAreaListFirst = new
List<JObject>(); foreach (var item in AreaListFirst) { var Second = from r in AreaList where r.Parent_ID == item.ID select r; //所有市的集合 List<JObject> JAreaListSecond = new List<JObject>(); ;
foreach (var item2 in Second) { var Three = from r in AreaList where r.Parent_ID == item2.ID select r; //所有區的集合 List<JObject> JAreaListThree = new List<JObject>(); ; foreach (var item3 in Three) { JObject obj1 = JObject.FromObject(new { id = item3.ID.ToString(), value =item3.Name }); JAreaListThree.Add(obj1); } JObject obj2 = JObject.FromObject(new { id = item2.ID.ToString(), value = item2.Name, childs = JAreaListThree }); JAreaListSecond.Add(obj2); } JObject obj3 = JObject.FromObject(new { id = item.ID.ToString(), value = item.Name, childs = JAreaListSecond }); //將吉林省放到第一位 if (item.Name == "吉林省") { JAreaListFirst.Insert(0, obj3); } else { JAreaListFirst.Add(obj3); } } string PP = Newtonsoft.Json.JsonConvert.SerializeObject(JAreaListFirst, Newtonsoft.Json.Formatting.Indented); HttpRuntime.Cache.Add("AreaName", PP, null, DateTime.MaxValue, System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, null); return PP; } else { return Data; } }

 

 

希望能找個更好點的。