关于json的操作,网上一搜一大把。避免重复造轮子,整理发布一个笔者在项目开发中经常用到的一个json实用帮助类,泛型实现,非常方便。不废话了,贴代码:
1、json操作的帮助类:
Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Web.Script.Serialization;
namespace DotNet.Common.Util
{
/// <summary>
/// Json操作帮助类
/// </summary>
public static class JsonHelper
{
#region DataContractJsonSerializer
/// <summary>
/// 对象转换成json
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="jsonObject">需要格式化的对象</param>
/// <returns>Json字符串</returns>
public static string DataContractJsonSerialize<T>(T jsonObject)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
string json = null;
using (MemoryStream ms = new MemoryStream()) //定义一个stream用来存发序列化之后的内容
{
serializer.WriteObject(ms, jsonObject);
json = Encoding.UTF8.GetString(ms.GetBuffer()); //将stream读取成一个字符串形式的数据,并且返回
ms.Close();
}
return json;
}
/// <summary>
/// json字符串转换成对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="json">要转换成对象的json字符串</param>
/// <returns></returns>
public static T DataContractJsonDeserialize<T>(string json)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
T obj = default(T);
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
obj = (T)serializer.ReadObject(ms);
ms.Close();
}
return obj;
}
#endregion
#region JavaScriptSerializer ms这里的两个方法已经out了
//“System.Web.Script.Serialization.JavaScriptSerializer.JavaScriptSerializer()”已过时:
//“The recommended alternative is System.Runtime.Serialization.DataContractJsonSerializer.”
/// <summary>
/// 对象转换成json
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="jsonObject"></param>
/// <returns></returns>
public static string JavaScriptSerialize<T>(T jsonObject)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
StringBuilder sb = new StringBuilder();
serializer.Serialize(jsonObject, sb);
return sb.ToString();
}
/// <summary>
/// json字符串转换成对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="json"></param>
/// <returns></returns>
public static T JavaScriptDeserialize<T>(string json)
{
var result = new JavaScriptSerializer().Deserialize<T>(json);
return (T)result;
}
#endregion
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Web.Script.Serialization;
namespace DotNet.Common.Util
{
/// <summary>
/// Json操作帮助类
/// </summary>
public static class JsonHelper
{
#region DataContractJsonSerializer
/// <summary>
/// 对象转换成json
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="jsonObject">需要格式化的对象</param>
/// <returns>Json字符串</returns>
public static string DataContractJsonSerialize<T>(T jsonObject)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
string json = null;
using (MemoryStream ms = new MemoryStream()) //定义一个stream用来存发序列化之后的内容
{
serializer.WriteObject(ms, jsonObject);
json = Encoding.UTF8.GetString(ms.GetBuffer()); //将stream读取成一个字符串形式的数据,并且返回
ms.Close();
}
return json;
}
/// <summary>
/// json字符串转换成对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="json">要转换成对象的json字符串</param>
/// <returns></returns>
public static T DataContractJsonDeserialize<T>(string json)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
T obj = default(T);
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
obj = (T)serializer.ReadObject(ms);
ms.Close();
}
return obj;
}
#endregion
#region JavaScriptSerializer ms这里的两个方法已经out了
//“System.Web.Script.Serialization.JavaScriptSerializer.JavaScriptSerializer()”已过时:
//“The recommended alternative is System.Runtime.Serialization.DataContractJsonSerializer.”
/// <summary>
/// 对象转换成json
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="jsonObject"></param>
/// <returns></returns>
public static string JavaScriptSerialize<T>(T jsonObject)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
StringBuilder sb = new StringBuilder();
serializer.Serialize(jsonObject, sb);
return sb.ToString();
}
/// <summary>
/// json字符串转换成对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="json"></param>
/// <returns></returns>
public static T JavaScriptDeserialize<T>(string json)
{
var result = new JavaScriptSerializer().Deserialize<T>(json);
return (T)result;
}
#endregion
}
}
ps:需要添加System.ServiceModel.Web和System.Runtime.Serialization两个引用。
ps1:对时间、DataTable等特殊类型没有单独列出处理。
2、在页面中的调用方式如下:
Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
namespace WebTest
{
using DotNet.Common.WebForm;
using DotNet.Common.Model;
using EntCor.Hrm.Model;
using DotNet.Common.Util;
public partial class JsonTest : BasePage
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Company company = new Company { ID = 123456789, CompanyName = "test" };
List<Employee> listEmployees = new List<Employee>();
Employee employee = new Employee { ID = 1, UserName = "jeff wong", Password = "123456", Address = "北京", Birthday = DateTime.Now.AddYears(-25), IsLeave = false, RealName = "测试用户", State = "2" };
listEmployees.Add(employee);
employee = new Employee { ID = 2, UserName = "jeffery zhao", Password = "654321", Address = "上海", Birthday = DateTime.Now.AddYears(-25), IsLeave = false, RealName = "测试用户2", State = "2" };
listEmployees.Add(employee);
company.Employees = listEmployees;
//对象序列化为json
string jsonStr = DotNet.Common.Util.JsonHelper.DataContractJsonSerialize<Company>(company);//等价于过时的 string jsonStr = DotNet.Common.Util.JsonHelper.JavaScriptSerialize<Company>(company);
this.ltrContext.Text = jsonStr;
//json字符串反序列化为对象
Company jsonCompany = DotNet.Common.Util.JsonHelper.DataContractJsonDeserialize<Company>(jsonStr);
Company jsonJsCompany = DotNet.Common.Util.JsonHelper.JavaScriptDeserialize<Company>(jsonStr); //过时了
Response.Write("公司id:"+jsonCompany.ID);
Response.Write("<br/><br/>公司id:" + jsonJsCompany.ID);
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
namespace WebTest
{
using DotNet.Common.WebForm;
using DotNet.Common.Model;
using EntCor.Hrm.Model;
using DotNet.Common.Util;
public partial class JsonTest : BasePage
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Company company = new Company { ID = 123456789, CompanyName = "test" };
List<Employee> listEmployees = new List<Employee>();
Employee employee = new Employee { ID = 1, UserName = "jeff wong", Password = "123456", Address = "北京", Birthday = DateTime.Now.AddYears(-25), IsLeave = false, RealName = "测试用户", State = "2" };
listEmployees.Add(employee);
employee = new Employee { ID = 2, UserName = "jeffery zhao", Password = "654321", Address = "上海", Birthday = DateTime.Now.AddYears(-25), IsLeave = false, RealName = "测试用户2", State = "2" };
listEmployees.Add(employee);
company.Employees = listEmployees;
//对象序列化为json
string jsonStr = DotNet.Common.Util.JsonHelper.DataContractJsonSerialize<Company>(company);//等价于过时的 string jsonStr = DotNet.Common.Util.JsonHelper.JavaScriptSerialize<Company>(company);
this.ltrContext.Text = jsonStr;
//json字符串反序列化为对象
Company jsonCompany = DotNet.Common.Util.JsonHelper.DataContractJsonDeserialize<Company>(jsonStr);
Company jsonJsCompany = DotNet.Common.Util.JsonHelper.JavaScriptDeserialize<Company>(jsonStr); //过时了
Response.Write("公司id:"+jsonCompany.ID);
Response.Write("<br/><br/>公司id:" + jsonJsCompany.ID);
}
}
}
}
ps:Company和Employee分别对应公司类和员工类。
关于json的其他学习资源,推荐JSON In Code 和JSON
demo下载地址:demo