Json串序列化和反序列化

初始化一个数据字典,将它转化为json串,并将转化后的json串再转化为字典对象
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebService.ServiceReference;

using System.Text;
using System.Web.Script.Serialization;
using System.Data;


/// <summary>
/// 初始化字典里面的内容
/// </summary>
/// <returns></returns>
private SortedDictionary<string, string> GetBaseParamDict()
{
SortedDictionary<string, string> sdBase = new SortedDictionary<string, string>();
            sdBase.Add("陕西", "西安");
            sdBase.Add("北京", "北京");
            sdBase.Add("广东", "广州");
            sdBase.Add("山西", "太原");
            sdBase.Add("四川", "成都");
            return sdBase;
}

/// <summary>
        /// 将对象序列化为json串
        /// </summary>
        /// <param name="obj">object可以是数据字典</param>
        /// <returns>json串</returns>
        private string DiceToJson2(object obj)
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            return jss.Serialize(obj);
        }
        
        /// <summary>
        /// 将Json串反序列化为字典
        /// </summary>
        /// <param name="str">json串</param>
        /// <returns>泛型的数据字典<string,string></returns>
        private SortedDictionary<string,string> JsonToDice(string str)
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            SortedDictionary<string, string> dice = new SortedDictionary<string, string>();

            dice = jss.Deserialize<SortedDictionary<string,string>>(str);

            foreach (var item in dice)
            {
                Response.Write(item.Key + item.Value);
            }

            return dice;
        }


未完待续...

猜你喜欢

转载自yh-fly.iteye.com/blog/2277645