C#操作json类型数据
2018-06-18 02:59:08来源:未知 阅读 ()
将对象序列化为 JavaScript 对象表示法 (JSON),并将 JSON 数据反序列化为对象。 此类不能继承。
// msdn 例子:
- namespace SL_DataContractJsonSerializer
- {
- public partial class Page : UserControl
- {
- public Page()
- {
- InitializeComponent();
- }
- //This uses an event handler, not SL data binding
- void OnClick(object sender, EventArgs args)
- {
- txtOutput1.Text = "Create a User object and serialize it.";
- string json = WriteFromObject();
- txtOutput2.Text = json.ToString(); // Displays: {"Age":42,"Name":"Bob"}
- txtOutput3.Text = "Deserialize the data to a User object.";
- string jsonString = "{'Name':'Bill', 'Age':53}";
- User deserializedUser = ReadToObject(jsonString);
- txtOutput4.Text = deserializedUser.Name; // Displays: Bill
- txtOutput5.Text = deserializedUser.Age.ToString(); // Displays: 53
- }
- // Create a User object and serialize it to a JSON stream.
- public static string WriteFromObject()
- {
- //Create User object.
- User user = new User("Bob", 42);
- //Create a stream to serialize the object to.
- MemoryStream ms = new MemoryStream();
- // Serializer the User object to the stream.
- DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(User));
- ser.WriteObject(ms, user);
- byte[] json = ms.ToArray();
- ms.Close();
- return Encoding.UTF8.GetString(json, 0, json.Length);
- }
- // Deserialize a JSON stream to a User object.
- public static User ReadToObject(string json)
- {
- User deserializedUser = new User();
- MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json));
- DataContractJsonSerializer ser = new DataContractJsonSerializer(deserializedUser.GetType());
- deserializedUser = ser.ReadObject(ms) as User;
- ms.Close();
- return deserializedUser;
- }
- }
- [DataContract]
- public class User
- {
- [DataMember]
- public string Name { get; set; }
- [DataMember]
- public int Age { get; set; }
- public User() { }
- public User(string newName, int newAge)
- {
- Name = newName;
- Age = newAge;
- }
- }
- }
可以抽象成如下类:
- public class JsonHelper
- {
- /// <summary>
- /// 生成Json格式
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="obj"></param>
- /// <returns></returns>
- public static string GetJson<T>(T obj)
- {
- DataContractJsonSerializer json = new DataContractJsonSerializer(obj.GetType());
- using (MemoryStream stream = new MemoryStream())
- {
- json.WriteObject(stream, obj);
- string szJson = Encoding.UTF8.GetString(stream.ToArray());
- return szJson;
- }
- }
- /// <summary>
- /// 获取Json的Model
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="szJson"></param>
- /// <returns></returns>
- public static T ParseFromJson<T>(string szJson)
- {
- T obj = Activator.CreateInstance<T>();
- using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson)))
- {
- DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
- return (T)serializer.ReadObject(ms);
- }
- }
- }
- /// <summary>
- /// 反回JSON数据到前台
- /// </summary>
- /// <param name="dt">数据表</param>
- /// <returns>JSON字符串</returns>
- public string DataTableToJson(DataTable dt)
- {
- StringBuilder JsonString = new StringBuilder();
- if (dt != null && dt.Rows.Count > 0)
- {
- JsonString.Append("{ ");
- JsonString.Append("\"TableInfo\":[ ");
- for (int i = 0; i < dt.Rows.Count; i++)
- {
- JsonString.Append("{ ");
- for (int j = 0; j < dt.Columns.Count; j++)
- {
- if (j < dt.Columns.Count - 1)
- {
- JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\",");
- }
- else if (j == dt.Columns.Count - 1)
- {
- JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\"");
- }
- }
- if (i == dt.Rows.Count - 1)
- {
- JsonString.Append("} ");
- }
- else
- {
- JsonString.Append("}, ");
- }
- }
- JsonString.Append("]}");
- return JsonString.ToString();
- }
- else
- {
- return null;
- }
- }
//还有一种方式操作json类型数据:
- public static class JsonTableHelper
- {
- /// <summary>
- /// 返回对象序列化
- /// </summary>
- /// <param name="obj">源对象</param>
- /// <returns>json数据</returns>
- public static string ToJson(this object obj)
- {
- JavaScriptSerializer serialize = new JavaScriptSerializer();
- return serialize.Serialize(obj);
- }
- /// <summary>
- /// 控制深度
- /// </summary>
- /// <param name="obj">源对象</param>
- /// <param name="recursionDepth">深度</param>
- /// <returns>json数据</returns>
- public static string ToJson(this object obj, int recursionDepth)
- {
- JavaScriptSerializer serialize = new JavaScriptSerializer();
- serialize.RecursionLimit = recursionDepth;
- return serialize.Serialize(obj);
- }
- /// <summary>
- /// DataTable转为json
- /// </summary>
- /// <param name="dt">DataTable</param>
- /// <returns>json数据</returns>
- public static string ToJson(DataTable dt)
- {
- Dictionary<string, object> dic = new Dictionary<string, object>();
- int index = 0;
- foreach (DataRow dr in dt.Rows)
- {
- Dictionary<string, object> result = new Dictionary<string, object>();
- foreach (DataColumn dc in dt.Columns)
- {
- result.Add(dc.ColumnName, dr[dc].ToString());
- }
- dic.Add(index.ToString(), result);
- index++;
- }
- return ToJson(dic);
- }
- }
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有
下一篇:.NET中的IO操作之文件流
- C++ 自动转换和强制类型转换(用户自定义类类型) 2020-06-10
- QT5 解析JSON文件 2020-06-09
- SWIG 3 中文手册——11. 类型映射 2020-06-07
- Visual Studio 2019提示不能将const char*类型的值分配到con 2020-06-07
- C++ 共用体 2020-06-05
IDC资讯: 主机资讯 注册资讯 托管资讯 vps资讯 网站建设
网站运营: 建站经验 策划盈利 搜索优化 网站推广 免费资源
网络编程: Asp.Net编程 Asp编程 Php编程 Xml编程 Access Mssql Mysql 其它
服务器技术: Web服务器 Ftp服务器 Mail服务器 Dns服务器 安全防护
软件技巧: 其它软件 Word Excel Powerpoint Ghost Vista QQ空间 QQ FlashGet 迅雷
网页制作: FrontPages Dreamweaver Javascript css photoshop fireworks Flash