分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 前端开发

ASP.NET2.0 Newtonsoft.Json 操作类分享

发布时间:2023-09-06 01:59责任编辑:彭小芳关键词:.NET

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

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved