.net json序列化组件Json.NET(Newtonsoft.Json)

    Json.NET(Newtonsoft.Json)是.Net 框架下比较流行的一款高效json序列化开源组件,支持.Net Framework 2.0 到 4.5+,并且可用于.Net各种环境Asp.net,Silverlight,Windows Phone,Windows 8等等.更多特性移步开源首页:http://json.codeplex.com/

性能

Json.NET 、DataContractJsonSerializer、JavascriptSeriallizer性能测试结果对比,还不错吧。

引用

方式1.下载解压引用Newtonsoft.Json.dll

下载地址http://json.codeplex.com/releases/view/105633

方式2:Nuget安装

PM> Install-Package Newtonsoft.Json

序列化与反序列

1.基本用法,首先引用Newtonsoft.Json命名空间,定义好与json同结构的的类用于转换

复制代码
Software software = new  Software{ SoftID=1, 
                SoftName="限时免费" ,
                DownloadUrl="http://itunes.apple.com/cn/app/id427577372?mt=8",
                ReleaseTime=DateTime.Now
            };

//序列化
 string jsonStr = JsonConvert.SerializeObject(software);

//反序列化
Software objSoftware =JsonConvert.DeserializeObject<Software>(jsonStr);
Console.WriteLine(jsonStr);
复制代码

序列化输出

未命名

2.时间格式处理,DateTime类型序列化默认序列化如上,这种格式在其它客户端很难读取,或者想按自己的格式化

Newtonsoft.Json.Converters.IsoDateTimeConverter timeConverter = new Newtonsoft.Json.Converters.IsoDateTimeConverter();
timeConverter.DateTimeFormat = "yyyy年MM月dd日 HH:mm:ss";
Console.WriteLine(JsonConvert.SerializeObject(software, timeConverter));

输出结果:

未命名

3.匿名类型序列化,这种方法无需事先定义与json同结构的类就能反序列化

复制代码
//Json字符串
 string jsonStr = @"{result:-1,desc:'参数错误,请检查格式'}";

 //反序列化
 var obj = JsonConvert.DeserializeAnonymousType(jsonStr, new { result = 0, desc = string.Empty });
 Console.WriteLine(string.Format("result:{0} desc:{1}", obj.result, obj.desc));
复制代码

 

4.快速定位节点,用于快速处理或者json结构较为复杂的字符串,又不想定义对应转移类,如

复制代码
{"weatherinfo":{"city":"福州","city_en":"fuzhou","date_y":"2013年5月4日","date":"","week":"星期六","fchh":"18","cityid":"101230101","temp1":"16℃~21℃","temp2":"16℃~23℃","temp3":"17℃~24℃","temp4":"16℃~26℃","temp5":"17℃~29℃","temp6":"18℃~28℃","tempF1":"60.8℉~69.8℉","tempF2":"60.8℉~73.4℉","tempF3":"62.6℉~75.2℉","tempF4":"60.8℉~78.8℉","tempF5":"62.6℉~84.2℉","tempF6":"64.4℉~82.4℉","weather1":"阵雨","weather2":"阵雨转阴","weather3":"阴转雷阵雨","weather4":"阵雨转雷阵雨","weather5":"阵雨转多云","weather6":"多云转中雨","img1":"3","img2":"99","img3":"3","img4":"2","img5":"2","img6":"4","img7":"3","img8":"4","img9":"3","img10":"1","img11":"1","img12":"8","img_single":"3","img_title1":"阵雨","img_title2":"阵雨","img_title3":"阵雨","img_title4":"阴","img_title5":"阴","img_title6":"雷阵雨","img_title7":"阵雨","img_title8":"雷阵雨","img_title9":"阵雨","img_title10":"多云","img_title11":"多云","img_title12":"中雨","img_title_single":"阵雨","wind1":"微风","wind2":"微风","wind3":"微风","wind4":"微风","wind5":"微风","wind6":"微风","fx1":"微风","fx2":"微风","fl1":"小于3级","fl2":"小于3级","fl3":"小于3级","fl4":"小于3级","fl5":"小于3级","fl6":"小于3级","index":"舒适","index_d":"建议着薄型套装或牛仔衫裤等春秋过渡装。年老体弱者宜着套装、夹克衫等。","index48":"舒适","index48_d":"建议着薄型套装或牛仔衫裤等春秋过渡装。年老体弱者宜着套装、夹克衫等。","index_uv":"弱","index48_uv":"最弱","index_xc":"不宜","index_tr":"适宜","index_co":"舒适","st1":"19","st2":"14","st3":"25","st4":"14","st5":"23","st6":"16","index_cl":"较不宜","index_ls":"不太适宜","index_ag":"易发"}}
复制代码

读取weatherinfo下的weather1

 var obj = JObject.Parse(html);
 string weather1 = (string)obj["weatherinfo"]["weather1"];

快速方便吧~~

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JSON数据格式简洁,用于数据的持久化和对象传输很实用。 java下有个大名鼎鼎的阿里巴巴开源的Java的JSON处理器 fastjson.net也有个.net版的fastjson。这里是作者做的性能测试:代码调用namespace test {     class Program     {         static void Main(string[] args)         {             var zoo1 = new zoo();             zoo1.animals = new List<animal>();             zoo1.animals.Add(new cat() { Name = "hello kitty", legs = 4 });             zoo1.animals.Add(new dog() { Name = "dog1", tail = true });             string json= fastJSON.JSON.Instance.ToJSON(zoo1); //序列化             var z = fastJSON.JSON.Instance.ToObject<zoo>(json); //反序列化             Console.WriteLine(z.animals[0].Name);             Console.Read();         }     }     public class animal { public string Name { get; set; } }     public class cat : animal { public int legs { get; set; } }     public class dog : animal { public bool tail { get; set; } }     public class zoo { public List<animal> animals { get; set; }  }基本的调用就是这么简单! 需要注意的是要反序列化的类好像必须声明为public的。快速的秘密 大体浏览了一下代码,发现之所以快速的原因是作者利用反射时Emit了大量的IL代码:internal object FastCreateInstance(Type objtype)         {             try             {                 CreateObject c = null;                 if (_constrcache.TryGetValue(objtype, out c))                 {                     return c();                 }                 else                 {                     if (objtype.IsClass)                      {                         DynamicMethod dynMethod = new DynamicMethod("_", objtype, null);                         ILGenerator ilGen = dynMethod.GetILGenerator();                         ilGen.Emit(OpCodes.Newobj, objtype.GetConstructor(Type.EmptyTypes));                         ilGen.Emit(OpCodes.Ret);                         c = (CreateObject)dynMethod.CreateDelegate(typeof(CreateObject));                         _constrcache.Add(objtype, c);                     }                     else // structs                     {                              DynamicMethod dynMethod = new DynamicMethod("_",                             MethodAttributes.Public | MethodAttributes.Static,                             CallingConventions.Standard,                             typeof(object),                             null,                             objtype, false);                         ILGenerator ilGen = dynMethod.GetILGenerator();                         var lv = ilGen.DeclareLocal(objtype);                         ilGen.Emit(OpCodes.Ldloca_S, lv);                         ilGen.Emit(OpCodes.Initobj, objtype);                         ilGen.Emit(OpCodes.Ldloc_0);                         ilGen.Emit(OpCodes.Box, objtype);                         ilGen.Emit(OpCodes.Ret);                         c = (CreateObject)dynMethod.CreateDelegate(typeof(CreateObject));                         _constrcache.Add(objtype, c);                     }                     return c();                 }             }             catch (Exception exc)             {                 throw new Exception(string.Format("Failed to fast create instance for type '{0}' from assemebly '{1}'",                     objtype.FullName, objtype.AssemblyQualifiedName), exc);             }         }更多教程请参考:http://www.codeproject.com/Articles/159450/fastJSON 标签:fastjson  json

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值