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 操作请求.
来源: http://www.bubuko.com/infodetail-2638521.html