首页 > 代码库 > Json.net

Json.net


Json.net 效率
image


Json.net 的特性
image
 
1.net 集合

1.1 无序集合 Dictionary,Hashtable
image


Hashtable
ht = new Hashtable();ht.Add("string", "Hashtable");ht.Add("DateTime", System.DateTime.Now);ht.Add("int", 10);textBox2.Text = JsonConvert.SerializeObject(ht, Newtonsoft.Json.Formatting.Indented);Dictionary<object, object> dict = new Dictionary<object, object>();dict.Add("string", "Dictionary");dict.Add("DateTime", System.DateTime.Now);dict.Add("int", 10);textBox2.Text += "\r\n" + JsonConvert.SerializeObject(dict, Newtonsoft.Json.Formatting.Indented);


看下效果:
7T5W9P1WKX(H{@C{_O`V`(K

1.2 有序集合 DataTable,List,Array
image 


DataTable
dt = new DataTable();dt.Columns.Add(new DataColumn("string",typeof(string)));dt.Columns.Add(new DataColumn("DateTime", typeof(DateTime)));dt.Columns.Add(new DataColumn("int", typeof(int)));DataRow dr = dt.NewRow();dr[0] = "test1";dr[1] = System.DateTime.Now;dr[2] = 10;dt.Rows.Add(dr);DataRow dr1 = dt.NewRow();dr1[0] = "test2";dr1[1] = System.DateTime.Now;dr1[2] = 10;dt.Rows.Add(dr1);textBox2.Text = JsonConvert.SerializeObject(dt, Newtonsoft.Json.Formatting.Indented);


看下效果:
image

 


2 JObject 对象
2.1 不用实体序列化Json 对象

             JObject obj = new JObject()                {                    {"UserName","wwwwww"},                    {"Vipgrade",30},                    {                        "TravelMoney",new JArray                         {                             "任我游",                             "任我住",                             "任我行",                         }                    }                };                textBox2.Text = JsonConvert                    .SerializeObject(obj, Newtonsoft.Json.Formatting.Indented);                JObject obj1 = new JObject();                obj1.Add("userName", JToken.FromObject("wwwwww"));                obj1.Add("Vipgarde", JToken.FromObject(30));                obj1.Add("TravelMoney", JToken.FromObject(                        new List<KeyAndValue>(){                            new KeyAndValue(){                                Key="50",                                Value = http://www.mamicode.com/"任我游"                            },                            new KeyAndValue()                            {                                Key="100",                                Value = http://www.mamicode.com/"任我行"                            }                        }                    ));                textBox2.Text += "\r\n" + JsonConvert

 


public class
KeyAndValue{ [JsonProperty(PropertyName = "金额")] public string Key { get; set; } [JsonProperty(PropertyName = "名称")] public string Value { get; set; } public override string ToString() { return "(" + this.Key.ToString() + ")" + this.Value.ToString(); }}


看下效果:
image 

2.2 Linq To Json 支持

string s = @"{        List: [            {                ‘Hotelid‘: 1,                ‘HotelName‘: ‘保安‘,                ‘En_HotelName‘: ‘baoan‘            },            {                ‘Hotelid‘: 2,                ‘HotelName‘: ‘华庭宾馆‘,                ‘En_HotelName‘: ‘huating‘            }        ]    }";textBox1.Text = s;JObject obj = JObject.Parse(textBox1.Text);var TempInfo = from n in obj.Property("List").ToList()[0]               select new               {                   hotelid = n.SelectToken("Hotelid"),                   HotelName = n.SelectToken("HotelName")               };foreach (var a in TempInfo){    MessageBox.Show(((JValue)a.hotelid).Value.ToString() + a.HotelName);}textBox2.Text = JsonConvert.SerializeObject(TempInfo, Newtonsoft.Json.Formatting.Indented);


看下效果:
image 

3 Json 动态效果
可以根据你的Value 值来进行Key值得显示。

 
//会员等级   public enum VipGrade   {       Gold = 20,       Silver = 10,       diamond = 30   }   public class Cusomter   {       public Cusomter(int _ID, string _UserName, VipGrade _vipGrade,int _integral)       {           ID = _ID;            UserName = _UserName;            vipGrade = _vipGrade;           integral = _integral;       }       /// <summary>       /// ID       /// </summary>       public int ID       {           get;           set;       }       /// <summary>       /// 客户名称       /// </summary>       public string UserName       {           get;           set;       }       /// <summary>       /// 会员等级       /// </summary>       [JsonConverter(typeof(StringEnumConverter))]       public VipGrade vipGrade       {           get;           set;       }       /// <summary>       /// 积分       /// </summary>       public int integral       {           get;           set;       }   }

 


public class
HideintegralContractResolver : DefaultContractResolver{ private readonly int integral; private readonly VipGrade vipgrade; public HideintegralContractResolver(VipGrade _vipgrade,int _integral) { integral = _integral; vipgrade = _vipgrade; } protected override IList<JsonProperty> CreateProperties(Type type,MemberSerialization memberSerialization) { IList<JsonProperty> list = base.CreateProperties(type, memberSerialization); list[3].ShouldSerialize = x => { Cusomter e = (Cusomter)x; if (e.integral > integral && e.vipGrade.GetHashCode() >= vipgrade.GetHashCode()) { return e.integral == e.integral; } else { return e.integral != e.integral; } }; return list; }}

 


List
<Cusomter> list = new List<Cusomter>();list.Add(new Cusomter(1, "张三", VipGrade.diamond, 20000));list.Add(new Cusomter(2, "李四", VipGrade.Gold, 3000));list.Add(new Cusomter(3, "王五", VipGrade.Silver, 4000));textBox1.Text = JsonConvert.SerializeObject(list, Newtonsoft.Json.Formatting.Indented);var settings = new JsonSerializerSettings();//积分担保 > 金牌用户且积分>10000的用户,序列化显示积分settings.ContractResolver = new HideintegralContractResolver(VipGrade.Gold, 10000);textBox2.Text = JsonConvert.SerializeObject(list, Newtonsoft.Json.Formatting.Indented, settings);


看下效果:
image

4.异常处理
我们给Key:int_object(Int) 类型赋个String类型,一样可以序列化成功

public class JsonNetTest    {        public string str_object        {            get;            set;        }        public DateTime dt_object        {            get;            set;        }         public int int_object        {            get;            set;        }        public float flt_object        {            get;            set;        }        [OnDeserializing]        internal void OnDeserializingMethod(StreamingContext context)        {                }        [OnDeserialized]        internal void OnDeserializedMethod(StreamingContext context)        {        }        [OnError]        internal void OnError(StreamingContext context, ErrorContext errorContext)        {            if (errorContext.Member.ToString().Equals("int_object"))            {                errorContext.Handled = true;            }            else            {                errorContext.Handled = false;            }        }    }

 


JObject obj = new JObject(){ {"str_object","www\‘www"}, {"dt_object",DateTime.Now}, {"int_object","fsdafs"}, {"flt_object",10},};textBox1.Text = JsonConvert.SerializeObject(obj, Newtonsoft.Json.Formatting.Indented);JsonNetTest test = (JsonNetTest)JsonConvert.DeserializeObject<JsonNetTest>(obj.ToString());textBox2.Text = JsonConvert.SerializeObject(test, Newtonsoft.Json.Formatting.Indented);

 


看下效果:
R)KT~{YZSKT4UJC2XSD`LOW


代码下载

Json.net