JSON 是现在比较流行的数据交互格式,NET3.0+有自带类处理JSON,2.0的话需要借助Newtonsoft.Json来完成,不然自己写的话,很麻烦。
网上搜索下载 Newtonsoft.Json.Net20.dll (没有加群找群主拿),添加引用到项目当中。
/*添加引用*/using Newtonsoft.Json;using Newtonsoft.Json.Linq;using Newtonsoft.Json.Converters; ???????/* 序列化,返回JSON格式的字符串 */ ???????public static string DateTimeFormat = "yyyy‘-‘MM‘-‘dd‘T‘HH‘:‘mm‘:‘ss"; ???????public static string Encode(object o) ???????{ ???????????if (o == null || o.ToString() == "null") return null; ???????????if (o != null && (o.GetType() == typeof(String) || o.GetType() == typeof(string))) ???????????{ ???????????????return o.ToString(); ???????????} ???????????IsoDateTimeConverter dt = new IsoDateTimeConverter(); ???????????dt.DateTimeFormat = DateTimeFormat; ???????????return JsonConvert.SerializeObject(o, dt); ???????} ???????/* 反序列化,返回Object对象,可转指定类型 */ ???????public static object Decode(string json, Type type) ???????{ ???????????if (json == "") return null; ???????????try { return JsonConvert.DeserializeObject(json, type); } ???????????catch { return null; } ???????}
使用说明:
/* 1、当为普通的JSON对象,没有数组,没有嵌套时 */Dictionary<string, object> json = Decode("json字符串", typeof(Dictionary<string, object>)) as Dictionary<string, object>;/* 2、当为JSON数组对象时 */List<Dictionary<string, object>> attrs = Decode("json数组", typeof(List<Dictionary<string, object>>)) as List<Dictionary<string, object>>;/* 3、当为多重嵌套时 先Dictionary<string, object>获取第一层,再循环指定KEY获取数组解析就是1 2两种方式慢慢解析出来*/
当然,比较有针对性的话,也可以自己写MODEL类指定JSON转换。
以上基本能满足大部份JSON操作请求。
ASP.NET2.0 Newtonsoft.Json 操作类分享
原文地址:https://www.cnblogs.com/ubshoes/p/9161944.html