C#中如何将List<自定义>转为Json格式 及相关函数-DataContractJsonSerializer
对C#和.net使用List<自定义>和Json格式相互转化的方法进行总结
关于JSON的入门介绍见http://www.json.org/ ,或者百度,这里不赘述,不过通过下面的例子会有个更快捷和更直观的认识。
如Json格式[{"id":"1","name":"sara"},{"id":"2","name":"sara2"}]
自定义数据类型,用于List<>:
[DataContract] class Person { [DataMember] public int id; [DataMember] public string name; }
程序中使用:
首先加入引用:
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
using System.Text;
代码内容:
class Program { static void Main(string[] args) { //Product.GetAllSmartPhones(); List<Person> nums = new List<Person>(); nums.Add(new Person() { id=1, name="sara" }); nums.Add(new Person() { id=1, name="sylar" }); DataContractJsonSerializer json = new DataContractJsonSerializer(nums.GetType()); string szJson = ""; //序列化 using (MemoryStream stream = new MemoryStream()) { json.WriteObject(stream, nums); szJson = Encoding.UTF8.GetString(stream.ToArray()); } Console.WriteLine(szJson); Console.ReadLine(); } }
工程化时,可以对自定义数据结构重新定义一个类:
如:
public class TestListResult<T> : List<T>
{
public TestListResult()
{
this.Successed = false;
this.Message = "";
}
public bool Successed { get; set; }
public string Message { get; set; }
}
使用时同上在一个文件里一样
理解了以上原理,可以使用以下函数在项目中使用:
List<T>转Json
- public static string Obj2Json<T>(T data)
- {
- try
- {
- System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(data.GetType());
- using (MemoryStream ms = new MemoryStream())
- {
- serializer.WriteObject(ms, data);
- return Encoding.UTF8.GetString(ms.ToArray());
- }
- }
- catch
- {
- return null;
- }
- }
Json转List<T>
- public static Object Json2Obj(String json,Type t)
- {
- try
- {
- System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(t);
- using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
- {
- return serializer.ReadObject(ms);
- }
- }
- catch
- {
- return null;
- }
- }
DataTable 转Json
- public static string DataTable2Json(DataTable dt)
- {
- if (dt.Rows.Count == 0)
- {
- return "";
- }
- StringBuilder jsonBuilder = new StringBuilder();
- // jsonBuilder.Append("{");
- //jsonBuilder.Append(dt.TableName.ToString());
- jsonBuilder.Append("[");//转换成多个model的形式
- for (int i = 0; i < dt.Rows.Count; i++)
- {
- jsonBuilder.Append("{");
- for (int j = 0; j < dt.Columns.Count; j++)
- {
- jsonBuilder.Append("\"");
- jsonBuilder.Append(dt.Columns[j].ColumnName);
- jsonBuilder.Append("\":\"");
- jsonBuilder.Append(dt.Rows[i][j].ToString());
- jsonBuilder.Append("\",");
- }
- jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
- jsonBuilder.Append("},");
- }
- jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
- jsonBuilder.Append("]");
- // jsonBuilder.Append("}");
- return jsonBuilder.ToString();
- }
单个对象转JSON
- public static T Json2Obj<T>(string json)
- {
- T obj = Activator.CreateInstance<T>();
- using (System.IO.MemoryStream ms = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(json)))
- {
- System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
- return (T)serializer.ReadObject(ms);
- }
- }
将函数封装成类,更便于项目中引用:
- 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);
- }
- }
在Asp.net中前后台Json数据的传递
一、前台产生Json数据传递给后台处理
前台生成Json数据要使用javascript和json.js。
json.js 下载地址:http://www.json.org/json.js
前台代码:
- var people = [{ "UserName": "t1", "PassWord": "111111", "Sex": "男" },{ "UserName": "t2", "PassWord": "222222", "Sex": "女" }];
- var url = "Default.aspx?people=" + escape(people.toJSONString());
- request.open("POST", url, true);
- request.onreadystatechange = updatePage;
- request.send(null);
后台处理代码:
同上面的转化原理一样,我们先建立一个json数据类,便于List<>中使用。
- [DataContract]//序列化
- public class TestObj
- {
- [DataMember]
- public string UserName { get; set; }
- [DataMember]
- public string PassWord { get; set; }
- [DataMember]
- public string Sex { get; set; }
- public TestObj(string u,string p,string s)
- {
- UserName = u;
- PassWord = p;
- Sex = s;
- }
- }
对前台提交的Json数据相互转化函数
- //json 序列化
- public static string ToJsJson(object item)
- {
- DataContractJsonSerializer serializer = new DataContractJsonSerializer(item.GetType());
- using(MemoryStream ms=new MemoryStream())
- {
- serializer.WriteObject(ms, item);
- StringBuilder sb = new StringBuilder();
- sb.Append(Encoding.UTF8.GetString(ms.ToArray()));
- return sb.ToString();
- }
- }
- //反序列化
- public static T FromJsonTo<T>(string jsonString)
- {
- DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
- using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
- {
- T jsonObject = (T)ser.ReadObject(ms);
- return jsonObject;
- }
- }
在后台代码中调用以上函数进行对数据people的处理:
- //获取json字符串
- string jsonStr = Request["people"];
- List<TestObj> obj = Json.FromJsonTo<List<TestObj>>(jsonStr);
- foreach (TestObj item in obj)
- {
- Response.Write(string.Format("UserName:{0},Password:{1},Sex:{2}/r/n", item.UserName, item.PassWord, item.Sex));
- }
- Response.End();
最终的结果:
- List<TestObj> Users = new List<TestObj>();
- Users.Add(new TestObj("t1", "1", "男"));
- Users.Add(new TestObj("t2", "2", "女"));
- string json = Json.ToJsJson(Users);
- Response.Write(json);
- Response.End();
二、前台获取后台提交的Json数据
后台产生Json数据的方法如上原理中提到的:
- string Json;
- DataContractJsonSerializer json = new DataContractJsonSerializer(list.GetType());
- using (MemoryStream stream = new MemoryStream())
- {
- json.WriteObject(stream, list);
- Json = Encoding.UTF8.GetString(stream.ToArray());
- }
- return Json;
- /// <summary>
- /// Json的数据结构
- /// </summary>
- [DataContract]
- class ResultJson
- {
- [DataMember]
- public bool Result;
- [DataMember]
- public int Count;
- [DataMember]
- public string Message;
- }
前台获取后台返回的Json字符串:
- function updatePage() {
- if (request.readyState == 4) {
- if (request.status == 200) {
- var response = request.responseText;
- //转化成对象
- //方法1
- response = response.parseJSON();
- //方法2
- // response = eval("(" + response + ")");
- //对象访问方式
- document.getElementById("d1").innerHTML = response[1].Sex;
- //直接输出
- // document.getElementById("d1").innerHTML = response;
- }
- }
- }
复杂的Json字符串操作方法:
假如我们要转化的JSON字符串格式为:
- {
- "encoding":"UTF-8",
- "plug-ins":["python","c++","ruby"],
- "indent":{
- "length":3,
- "use_space":true
- }
- }
然后编写相应的序列化的类,注意下面Indent类加的属性:
- [DataContract]
- class Config
- {
- [DataMember(Order = 0)]
- public string encoding { get; set; }
- [DataMember(Order = 1)]
- public string[] plugins { get; set; }
- [DataMember(Order = 2)]
- public Indent indent { get; set; }
- }
- [DataContract]
- class Indent
- {
- [DataMember(Order = 0)]
- public int length { get; set; }
- [DataMember(Order = 1)]
- public bool use_space { get; set; }
- }
输出JSON字符串
- var config = new Config(){
- encoding = "UTF-8",
- plugins = new string[]{"python", "C++", "C#"},
- indent = new Indent(){ length = 4, use_space = false}
- };
- var serializer = new DataContractJsonSerializer(typeof(Config));
- var stream = new MemoryStream();
- serializer.WriteObject(stream, config);
- byte[] dataBytes = new byte[stream.Length];
- stream.Position = 0;
- stream.Read(dataBytes, 0, (int)stream.Length);
- string dataString = Encoding.UTF8.GetString(dataBytes);
- Console.WriteLine("JSON string is:");
- Console.WriteLine(dataString);
结果:
- JSON string is:
- {"encoding":"UTF-8","plugins":["python","C++","C#"],"indent":{"length":4,"use_space":false}}
读取Json字符串内容:
- var mStream = new MemoryStream(Encoding.Default.GetBytes(dataString));
- Config readConfig = (Config)serializer.ReadObject(mStream);
- Console.WriteLine("Encoding is: {0}", readConfig.encoding);
- foreach (string plugin in readConfig.plugins)
- {
- Console.WriteLine("plugins is: {0}", plugin);
- }
- Console.WriteLine("indent.length is: {0}", readConfig.indent.length);
- Console.WriteLine("indent.use_space is: {0}", readConfig.indent.use_space);
结果:
- Encoding is: UTF-8
- plugins is: python
- plugins is: C++
- plugins is: C#
- indent.length is: 4
- indent.use_space is: False