.NET下 JSON 的一些常用操作

时间:2022-09-16 15:00:20

1.JSON的序列化和反序列化

首先要先添加引用:.NET下 JSON 的一些常用操作

代码如下

 

[csharp] view plain copy print ?
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using Newtonsoft.Json;  
  6.   
  7. namespace PlayJSON  
  8. {  
  9.     class Program  
  10.     {  
  11.         static void Main(string[] args)  
  12.         {  
  13.             List<StuInfo> list = new List<StuInfo>() { new StuInfo{StuName="张三",StuSex="男",StuAge=11},  
  14.                                                        new StuInfo{StuName="李四",StuSex="男",StuAge=32},  
  15.                                                        new StuInfo{StuName="王翠花",StuSex="女",StuAge=64}  
  16.                                                       };  
  17.             string jsonStr = JavaScriptConvert.SerializeObject(list);  //将对象转换成json存储   
  18.             Console.WriteLine("JSON字符串"+jsonStr);  
  19.             Console.ReadLine();  
  20.   
  21.             List<StuInfo> newList = new List<StuInfo>();  
  22.   
  23.            newList = (List<StuInfo>)JavaScriptConvert.DeserializeObject(jsonStr,typeof(List<StuInfo>));   //反序列化   
  24.   
  25.             //StuInfo s = new StuInfo() { StuName = "阿龙", StuSex = "男", StuAge = 33 };   
  26.   
  27.             //string sigleJSON = JavaScriptConvert.SerializeObject(s);   
  28.   
  29.            //StuInfo newS = (StuInfo)JavaScriptConvert.DeserializeObject(sigleJSON);   
  30.            //Console.WriteLine("姓名:" + newS.StuName + "---性别:" + newS.StuSex + "--年龄:" + newS.StuAge + "\n\n");   
  31.   
  32.   
  33.            foreach (StuInfo item in newList)  
  34.            {  
  35.                Console.WriteLine("姓名:" + item.StuName + "---性别:" + item.StuSex + "--年龄:" + item.StuAge + "\n\n");  
  36.            }  
  37.             Console.ReadLine();  
  38.         }  
  39.     }  
  40.     public class StuInfo   
  41.     {  
  42.         public string StuName { setget; }  
  43.         public string StuSex { setget; }  
  44.         public int StuAge { setget; }  
  45.     }  
  46. }  
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;

namespace PlayJSON
{
class Program
{
static void Main(string[] args)
{
List<StuInfo> list = new List<StuInfo>() { new StuInfo{StuName="张三",StuSex="男",StuAge=11},
new StuInfo{StuName="李四",StuSex="男",StuAge=32},
new StuInfo{StuName="王翠花",StuSex="女",StuAge=64}
};
string jsonStr = JavaScriptConvert.SerializeObject(list); //将对象转换成json存储
Console.WriteLine("JSON字符串"+jsonStr);
Console.ReadLine();

List<StuInfo> newList = new List<StuInfo>();

newList = (List<StuInfo>)JavaScriptConvert.DeserializeObject(jsonStr,typeof(List<StuInfo>)); //反序列化

//StuInfo s = new StuInfo() { StuName = "阿龙", StuSex = "男", StuAge = 33 };

//string sigleJSON = JavaScriptConvert.SerializeObject(s);

//StuInfo newS = (StuInfo)JavaScriptConvert.DeserializeObject(sigleJSON);
//Console.WriteLine("姓名:" + newS.StuName + "---性别:" + newS.StuSex + "--年龄:" + newS.StuAge + "\n\n");


foreach (StuInfo item in newList)
{
Console.WriteLine("姓名:" + item.StuName + "---性别:" + item.StuSex + "--年龄:" + item.StuAge + "\n\n");
}
Console.ReadLine();
}
}
public class StuInfo
{
public string StuName { set; get; }
public string StuSex { set; get; }
public int StuAge { set; get; }
}
}

 

2.在web中

首先添加一个一般处理文件 Handler1.ashx:用来返回一个json

 

[csharp] view plain copy print ?
  1. /// <summary>   
  2.     /// Handler1 的摘要说明   
  3.     /// </summary>   
  4.     public class Handler1 : IHttpHandler  
  5.     {  
  6.   
  7.         public void ProcessRequest(HttpContext context)  
  8.         {  
  9.             context.Response.ContentType = "application/json";  
  10.   
  11.             List<StuInfo> list = new List<StuInfo>() { new StuInfo{StuName="张三",StuSex="男",StuAge=11},  
  12.                                                        new StuInfo{StuName="李四",StuSex="男",StuAge=32},  
  13.                                                        new StuInfo{StuName="王翠花",StuSex="女",StuAge=64}  
  14.                                                       };  
  15.             string jsonStr = JavaScriptConvert.SerializeObject(list);  
  16.   
  17.             context.Response.Write(jsonStr);  
  18.   
  19.             context.Response.End();  
  20.         }  
  21.   
  22.         public bool IsReusable  
  23.         {  
  24.             get  
  25.             {  
  26.                 return false;  
  27.             }  
  28.         }  
  29.     }  
  30.     public class StuInfo  
  31.     {  
  32.         public string StuName { setget; }  
  33.         public string StuSex { setget; }  
  34.         public int StuAge { setget; }  
  35.     }  
/// <summary>
/// Handler1 的摘要说明
/// </summary>
public class Handler1 : IHttpHandler
{

public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json";

List<StuInfo> list = new List<StuInfo>() { new StuInfo{StuName="张三",StuSex="男",StuAge=11},
new StuInfo{StuName="李四",StuSex="男",StuAge=32},
new StuInfo{StuName="王翠花",StuSex="女",StuAge=64}
};
string jsonStr = JavaScriptConvert.SerializeObject(list);

context.Response.Write(jsonStr);

context.Response.End();
}

public bool IsReusable
{
get
{
return false;
}
}
}
public class StuInfo
{
public string StuName { set; get; }
public string StuSex { set; get; }
public int StuAge { set; get; }
}


前台页面上的调用:这里采用jquery 的ajax请求

 

 

[csharp] view plain copy print ?
  1. <head runat="server">  
  2.     <title>JSON</title>  
  3.     <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>  
  4.     <script type="text/javascript">  
  5.         $(function () {  
  6.             $("#btnOK").click(function () {  
  7.                 $.ajax({  
  8.                     type: "JSON",  
  9.                     url: "Handler1.ashx",  
  10.                     data: null,  
  11.                     success: function (msg) {  
  12.                         var con="";  
  13.                         for (var i = 0; i < msg.length; i++) {  
  14.                             con += "姓名:" + msg[i].StuName + "--性别:" + msg[i].StuSex + "--" + "--年龄:" + msg[i].StuAge+"<br/>";  
  15.                         }  
  16.   
  17.                         $("#divContent").html("长度:" + msg.length + "--具体内容:<br/>" + con);  
  18.                     }  
  19.                 });  
  20.             });  
  21.         });  
  22.     </script>  
  23. </head>  
  24. <body>  
  25.     <form id="form1" runat="server">  
  26.     <div>  
  27.     <input type="button" id="btnOK" value="点我获得JSON数据" />  
  28.     <div id="divContent"></div>  
  29.     </div>  
  30.     </form>  
  31. </body>  
<head runat="server">
<title>JSON</title>
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$("#btnOK").click(function () {
$.ajax({
type: "JSON",
url: "Handler1.ashx",
data: null,
success: function (msg) {
var con="";
for (var i = 0; i < msg.length; i++) {
con += "姓名:" + msg[i].StuName + "--性别:" + msg[i].StuSex + "--" + "--年龄:" + msg[i].StuAge+"<br/>";
}

$("#divContent").html("长度:" + msg.length + "--具体内容:<br/>" + con);
}
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="button" id="btnOK" value="点我获得JSON数据" />
<div id="divContent"></div>
</div>
</form>
</body>

 

现在经常会用到json,因此经常会需要对其进行序列化和反序列化。,.NET Framewok 3.5也提供了JSON对象序列化和反序列化的类,这就是System.Runtime.Serialization.Json 命名空间下的 DataContractJsonSerializer 类。利用这个类,可以实现JSON对象的序列化和反序列化。

现在我提供一个类JSON对象序列化和反序列化的类供参考用:

[csharp] view plain copy print ?
  1. /// <summary>   
  2.     /// JSON帮助类。用于将对象转换为Json格式的字符串,或者将Json的字符串转化为对象。   
  3.     /// </summary>   
  4.     public static class JsonHelper  
  5.     {  
  6.         /// <summary>   
  7.         /// 将对象转化为Json字符串    
  8.         /// </summary>   
  9.         /// <typeparam name="T">源类型</typeparam>   
  10.         /// <param name="obj">源类型实例</param>   
  11.         /// <returns>Json字符串</returns>   
  12.         public static string GetJsonFromObj<T>(T obj)  
  13.         {  
  14.             DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(obj.GetType());  
  15.             using (MemoryStream ms = new MemoryStream())  
  16.             {  
  17.                 jsonSerializer.WriteObject(ms, obj);  
  18.                 return Encoding.UTF8.GetString(ms.ToArray());  
  19.             }  
  20.         }  
  21.   
  22.         /// <summary>   
  23.         /// 将Json字符串转化为对象   
  24.         /// </summary>   
  25.         /// <typeparam name="T">目标类型</typeparam>   
  26.         /// <param name="strJson">Json字符串</param>   
  27.         /// <returns>目标类型的一个实例</returns>   
  28.         public static T GetObjFromJson<T>(string strJson)  
  29.         {  
  30.             T obj = Activator.CreateInstance<T>();  
  31.             using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(strJson)))  
  32.             {  
  33.                 DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(obj.GetType());  
  34.                 return (T)jsonSerializer.ReadObject(ms);  
  35.             }  
  36.         }  
  37.   
  38.         /// <summary>   
  39.         /// 将DataTable转换为JSON字符串   
  40.         /// </summary>   
  41.         /// <param name="dt">数据表</param>   
  42.         /// <returns>JSON字符串</returns>   
  43.         public static string GetJsonFromDataTable(DataTable dt)  
  44.         {  
  45.             StringBuilder JsonString = new StringBuilder();  
  46.             if (dt != null && dt.Rows.Count > 0)  
  47.             {  
  48.                 JsonString.Append("{ ");  
  49.                 JsonString.Append("\"TableInfo\":[ ");  
  50.                 for (int i = 0; i < dt.Rows.Count; i++)  
  51.                 {  
  52.                     JsonString.Append("{ ");  
  53.                     for (int j = 0; j < dt.Columns.Count; j++)  
  54.                     {  
  55.                         if (j < dt.Columns.Count - 1)  
  56.                         {  
  57.                             JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\",");  
  58.                         }  
  59.                         else if (j == dt.Columns.Count - 1)  
  60.                         {  
  61.                             JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\"");  
  62.                         }  
  63.                     }  
  64.                     if (i == dt.Rows.Count - 1)  
  65.                     {  
  66.                         JsonString.Append("} ");  
  67.                     }  
  68.                     else  
  69.                     {  
  70.                         JsonString.Append("}, ");  
  71.                     }  
  72.                 }  
  73.                 JsonString.Append("]}");  
  74.                 return JsonString.ToString();  
  75.             }  
  76.             else  
  77.             {  
  78.                 return null;  
  79.             }  
  80.         }  
  81.   
  82.         /// <summary>    
  83.         /// 将对象转化为Json字符串    
  84.         /// </summary>    
  85.         /// <param name="obj">源对象</param>    
  86.         /// <returns>json数据</returns>    
  87.         public static string ObjToJson(this object obj)  
  88.         {  
  89.             JavaScriptSerializer serialize = new JavaScriptSerializer();  
  90.             return serialize.Serialize(obj);  
  91.         }  
  92.   
  93.         /// <summary>    
  94.         /// 将Json字符串转化为对象   
  95.         /// </summary>    
  96.         /// <param name="strJson">Json字符串</param>    
  97.         /// <returns>目标对象</returns>   
  98.         public static T JsonToObj<T>(string strJson)  
  99.         {  
  100.             JavaScriptSerializer serialize = new JavaScriptSerializer();  
  101.             return serialize.Deserialize<T>(strJson);  
  102.         }  
  103.   
  104.         /// <summary>    
  105.         /// 将对象转化为Json字符串(控制深度 )   
  106.         /// </summary>    
  107.         /// <param name="obj">源对象</param>    
  108.         /// <param name="recursionDepth">深度</param>    
  109.         /// <returns>json数据</returns>    
  110.         public static string ObjToJson(this object obj, int recursionDepth)  
  111.         {  
  112.             JavaScriptSerializer serialize = new JavaScriptSerializer();  
  113.             serialize.RecursionLimit = recursionDepth;  
  114.             return serialize.Serialize(obj);  
  115.         }  
  116.   
  117.         /// <summary>    
  118.         /// 将Json字符串转化为对象(控制深度 )   
  119.         /// </summary>    
  120.         /// <param name="strJson">Json字符串</param>    
  121.         /// <param name="recursionDepth">深度</param>    
  122.         /// <returns>目标对象</returns>   
  123.         public static T JsonToObj<T>(string strJson, int recursionDepth)  
  124.         {  
  125.             JavaScriptSerializer serialize = new JavaScriptSerializer();  
  126.             serialize.RecursionLimit = recursionDepth;  
  127.             return serialize.Deserialize<T>(strJson);  
  128.         }  
  129.   
  130.         /// <summary>    
  131.         /// 将DataTable转换为JSON字符串   
  132.         /// </summary>    
  133.         /// <param name="dt">DataTable</param>    
  134.         /// <returns>json数据</returns>    
  135.         public static string DataTableToJson(DataTable dt)  
  136.         {  
  137.             Dictionary<stringobject> dic = new Dictionary<stringobject>();  
  138.   
  139.             int index = 0;  
  140.             foreach (DataRow dr in dt.Rows)  
  141.             {  
  142.                 Dictionary<stringobject> result = new Dictionary<stringobject>();  
  143.   
  144.                 foreach (DataColumn dc in dt.Columns)  
  145.                 {  
  146.                     result.Add(dc.ColumnName, dr[dc].ToString());  
  147.                 }  
  148.                 dic.Add(index.ToString(), result);  
  149.                 index++;  
  150.             }  
  151.             return ObjToJson(dic);  
  152.         }  
  153.     }  
/// <summary>
/// JSON帮助类。用于将对象转换为Json格式的字符串,或者将Json的字符串转化为对象。
/// </summary>
public static class JsonHelper
{
/// <summary>
/// 将对象转化为Json字符串
/// </summary>
/// <typeparam name="T">源类型</typeparam>
/// <param name="obj">源类型实例</param>
/// <returns>Json字符串</returns>
public static string GetJsonFromObj<T>(T obj)
{
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(obj.GetType());
using (MemoryStream ms = new MemoryStream())
{
jsonSerializer.WriteObject(ms, obj);
return Encoding.UTF8.GetString(ms.ToArray());
}
}

/// <summary>
/// 将Json字符串转化为对象
/// </summary>
/// <typeparam name="T">目标类型</typeparam>
/// <param name="strJson">Json字符串</param>
/// <returns>目标类型的一个实例</returns>
public static T GetObjFromJson<T>(string strJson)
{
T obj = Activator.CreateInstance<T>();
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(strJson)))
{
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(obj.GetType());
return (T)jsonSerializer.ReadObject(ms);
}
}

/// <summary>
/// 将DataTable转换为JSON字符串
/// </summary>
/// <param name="dt">数据表</param>
/// <returns>JSON字符串</returns>
public static string GetJsonFromDataTable(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;
}
}

/// <summary>
/// 将对象转化为Json字符串
/// </summary>
/// <param name="obj">源对象</param>
/// <returns>json数据</returns>
public static string ObjToJson(this object obj)
{
JavaScriptSerializer serialize = new JavaScriptSerializer();
return serialize.Serialize(obj);
}

/// <summary>
/// 将Json字符串转化为对象
/// </summary>
/// <param name="strJson">Json字符串</param>
/// <returns>目标对象</returns>
public static T JsonToObj<T>(string strJson)
{
JavaScriptSerializer serialize = new JavaScriptSerializer();
return serialize.Deserialize<T>(strJson);
}

/// <summary>
/// 将对象转化为Json字符串(控制深度 )
/// </summary>
/// <param name="obj">源对象</param>
/// <param name="recursionDepth">深度</param>
/// <returns>json数据</returns>
public static string ObjToJson(this object obj, int recursionDepth)
{
JavaScriptSerializer serialize = new JavaScriptSerializer();
serialize.RecursionLimit = recursionDepth;
return serialize.Serialize(obj);
}

/// <summary>
/// 将Json字符串转化为对象(控制深度 )
/// </summary>
/// <param name="strJson">Json字符串</param>
/// <param name="recursionDepth">深度</param>
/// <returns>目标对象</returns>
public static T JsonToObj<T>(string strJson, int recursionDepth)
{
JavaScriptSerializer serialize = new JavaScriptSerializer();
serialize.RecursionLimit = recursionDepth;
return serialize.Deserialize<T>(strJson);
}

/// <summary>
/// 将DataTable转换为JSON字符串
/// </summary>
/// <param name="dt">DataTable</param>
/// <returns>json数据</returns>
public static string DataTableToJson(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 ObjToJson(dic);
}
}

 

使用如下:

 

[csharp] view plain copy print ?
  1. public partial class WebForm1 : System.Web.UI.Page  
  2.     {  
  3.         protected void Page_Load(object sender, EventArgs e)  
  4.         {  
  5.   
  6.         }  
  7.   
  8.         protected void Button1_Click(object sender, EventArgs e)  
  9.         {  
  10.             //反序列化成对象        
  11.             String strJson = "{\"Name\":\"Test123\",\"Url\":\"http://www.126.com/\"}";  
  12.             Person p1 = JsonHelper.GetObjFromJson<Person>(strJson);  
  13.             Response.Write("<li>" + p1.Name + " " + p1.Url);  
  14.             Person p2 = JsonHelper.JsonToObj<Person>(strJson);  
  15.             Response.Write("<li>" + p2.Name + " " + p2.Url);  
  16.         }  
  17.   
  18.         protected void Button2_Click(object sender, EventArgs e)  
  19.         {  
  20.             //对象的序列化    
  21.             String JSONString = string.Empty;  
  22.             Person p1 = new Person();  
  23.             p1.Name = "Test123'\"\n\r\t";  
  24.             p1.Url = "http://www.126.com/";  
  25.             JSONString = JsonHelper.GetJsonFromObj<Person>(p1);  
  26.             Response.Write("<li>" + JSONString);  
  27.             JSONString = JsonHelper.ObjToJson(p1);  
  28.             Response.Write("<li>" + JSONString);  
  29.         }  
  30.     }  
  31.   
  32.     /// <summary>    
  33.     /// 类对象需要标记为DataContractAttribute    
  34.     /// </summary>    
  35.     [DataContractAttribute]  
  36.     class Person  
  37.     {  
  38.         //成员需要标记为 DataMember    
  39.         [DataMember]  
  40.         public string Name { setget; }  
  41.         [DataMember]  
  42.         public string Url { setget; }  
  43.     }  
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

protected void Button1_Click(object sender, EventArgs e)
{
//反序列化成对象
String strJson = "{\"Name\":\"Test123\",\"Url\":\"http://www.126.com/\"}";
Person p1 = JsonHelper.GetObjFromJson<Person>(strJson);
Response.Write("<li>" + p1.Name + " " + p1.Url);
Person p2 = JsonHelper.JsonToObj<Person>(strJson);
Response.Write("<li>" + p2.Name + " " + p2.Url);
}

protected void Button2_Click(object sender, EventArgs e)
{
//对象的序列化
String JSONString = string.Empty;
Person p1 = new Person();
p1.Name = "Test123'\"\n\r\t";
p1.Url = "http://www.126.com/";
JSONString = JsonHelper.GetJsonFromObj<Person>(p1);
Response.Write("<li>" + JSONString);
JSONString = JsonHelper.ObjToJson(p1);
Response.Write("<li>" + JSONString);
}
}

/// <summary>
/// 类对象需要标记为DataContractAttribute
/// </summary>
[DataContractAttribute]
class Person
{
//成员需要标记为 DataMember
[DataMember]
public string Name { set; get; }
[DataMember]
public string Url { set; get; }
}

 

 

Json.NET json字符串反序列化为json对象 

 

 

 

如何将一个字符串转换为JSON对象呢?如果先创建一个类的话,那就太累了。

var o = new
{
   a = 1,
   b = "Hello, World!",
   c = new[] { 1, 2, 3 },
   d = new Dictionary<string, int> { { "x", 1 }, { "y", 2 } }
};

var json = JsonConvert.SerializeObject(o);

现在json是一个字符串。

第一种做法(匿名类):

var anonymous = new { a = 0, b = String.Empty, c = new int[0], d = new Dictionary<string, int>() };
var o2 = JsonConvert.DeserializeAnonymousType(json, anonymous);

Console.WriteLine(o2.b);
Console.WriteLine(o2.c[1]);

第二种做法(匿名类):

var o3 = JsonConvert.DeserializeAnonymousType(json, new { c = new int[0], d = new Dictionary<string, int>() });

Console.WriteLine(o3.d["y"]);

DeserializeAnonymousType 只是借助这个匿名对象参数(anonymous) 反射类型而已,也就是说它和反序列化结果并非同一个对象。正如 o3 那样,我们也可以只提取局部信息。

 

第三种做法(索引器):

实际上,我们也可以直接反序列化为 JObject,然后通过索引器直接访问。JObject、JProperty 等都继承自 JToken,它重载了基元类型转换操作符,我们可以直接得到实际结果。
var o2 = JsonConvert.DeserializeObject(json) as JObject;

Console.WriteLine((int)o2["a"]);
Console.WriteLine((string)o2["b"]);
Console.WriteLine(o2["c"].Values().Count());
Console.WriteLine((int)o2["d"]["y"]);